Itzik984 Itzik984 - 5 months ago 23
iOS Question

Drawing UIBezierPath on code generated UIVIew

I have a

UIView
added in code at run time.

I want to draw a
UIBezierPath
in it, but does this means i have to override the
drawRect
for UIView?

Or is there another way of drawing to it on the custom made
UIView
?

Here is the code for generating the
UIView
:

UIView* shapeView = [[UIView alloc]initWithFrame:CGRectMake(xOrigin,yOrigin+(i*MENU_BLOCK_FRAME_HEIGHT), self.shapeScroll.frame.size.width, MENU_BLOCK_FRAME_HEIGHT)];
shapeView.clipsToBounds = YES;


And here is the function to create and return a
UIBezierPath
:

- (UIBezierPath*)createPath
{
UIBezierPath* path = [[UIBezierPath alloc]init];
[path moveToPoint:CGPointMake(100.0, 50.0)];
[path addLineToPoint:CGPointMake(200.0,50.0)];
[path addLineToPoint:CGPointMake(200.0, 200.0)];
[path addLineToPoint:CGPointMake(100.0, 200.0)];
[path closePath];
return path;
}


Thanks!

Answer

It would be easier if you would use a CAShapeLayer, like this:

CAShapeLayer *shapeView = [[CAShapeLayer alloc] init];

And set its path:

[shapeView setPath:[self createPath].CGPath];

Finally add it:

[[self.view layer] addSublayer:shapeView];
Comments