0

I am working on a form of design project. In this project, you select an object and can change the color or size, or move.

Started a prototype of the app.

I will use UIBezierPath to draw the ways of the shapes, and will use CAShapeLayer to add to a sublayer of UIView.

This code draw one shape for example:

let insetRect = CGRect(x: 20, y: 20, width: 100, height: 100)
let path = UIBezierPath(roundedRect: insetRect, cornerRadius: 30)
UIColor.redColor().setFill()
path.fill()

path.lineWidth = 100
UIColor.blackColor().setStroke()
path.stroke()

let shapeLayer = CAShapeLayer()
shapeLayer.path = path.CGPath
shapeLayer.lineWidth = 1.0

self.view.layer.addSublayer(shapeLayer)

When the app starts, the shape is created without problems.

I wish I could click on the screen and automatically change the color (random) from shape.

Another problem: The shapes are random, and they rectangle, ellipse, rounded square. And due to these forms, I can not directly create on a View (reason for use the UIBezierPath).

Some can help me? I am trying to solve this for a few hours, and so far, found nothing.

James
  • 1,167
  • 1
  • 13
  • 37

1 Answers1

3

Instead of adding bezierPath as sub layer, you can use a custom view. Pass a bezier path coordinates and color to the view. Keep instance of bezier path at class level and draw in DrawRect: method.

When user touches view in controller, pass custom view message to change color and redraw it.

You can simply change bezier path color by using:

yourColor.setStroke();

You can force your view to redraw bezier with changed color using:

customView.setNeedsDisplay();

EDIT

CustomView.m

-(id) initWithPath:(UIBezierPath *) path color:(UIColor *) color
{
    if(self = [super init])
    {
        bezierPath = path;
        pathColor = color;
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    [bezierPath stroke];
}

In controller, you can initialize as,

CustomView *customView = [[CustomView alloc] initWithPath:yourBezierPath color:[UIColor redColor];
customView.frame = yourFrame;
[self.view addSubview:customView];

To change color,

[customView setPathColor:[UIColor greenColor];
[customView setNeedsDisplay];

Hope it helps!

NightFury
  • 13,436
  • 6
  • 71
  • 120