Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw UIBezierPaths in UIView without subclassing?

I'm brand new to using UIBezierPaths to draw shapes. All of the examples I have found so far involve first subclassing a view, then overriding the drawRect: method and doing the drawing within there, but I haven't been able to find anything that says with absolute certainty whether this is the only way to draw UIBezierPaths within a UIView, or if this is just the most pragmatic way.

Is there any other way (besides swizzling) to draw a UIBezierPath in a UIView without subclassing it?

like image 274
n00neimp0rtant Avatar asked Apr 14 '15 18:04

n00neimp0rtant


1 Answers

Another way to draw bezier paths without using drawRect is to use CAShapeLayers. Set the path property of a shape layer to a CGPath created from the bezier path. Add the shape layer as a sublayer to your view's layer.

    UIBezierPath *shape = [UIBezierPath bezierPathWithOvalInRect:self.view.bounds];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = shape.CGPath;
    shapeLayer.fillColor = [UIColor colorWithRed:.5 green:1 blue:.5 alpha:1].CGColor;
    shapeLayer.strokeColor = [UIColor blackColor].CGColor;
    shapeLayer.lineWidth = 2;

    [self.view.layer addSublayer:shapeLayer];
like image 107
rdelmar Avatar answered Oct 06 '22 23:10

rdelmar