n00neimp0rtant n00neimp0rtant -3 years ago 94
iOS Question

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?

Answer Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download