Draw UIBezierPaths in a UIView without a subclass?

I am new to using UIBezierPaths for drawing shapes. All the examples I have found so far include first subclassing the view, then overriding the drawRect: method and executing the drawing inside it, but I could not find anything that says with absolute certainty whether this is the only way to draw UIBezierPaths in UIView, or if this is the most pragmatic way.

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

+7
ios objective-c uikit uiview uibezierpath
source share
4 answers

Another way to draw bezel-less paths without using drawRect is to use CAShapeLayers. Set the shape layer path property for CGPath created from a bezier path. Add a form layer as a sublevel to your view 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]; 
+15
source share

Quick version of accepted answer:

  let shape = UIBezierPath(ovalInRect: view.bounds) let shapeLayer = CAShapeLayer() shapeLayer.path = shape.CGPath shapeLayer.fillColor = UIColor(red: 0.5, green: 1, blue: 0.5, alpha: 1).CGColor shapeLayer.strokeColor = UIColor.blackColor().CGColor shapeLayer.lineWidth = 2.0 view.layer.addSublayer(shapeLayer) 
+5
source share

You can: 1) map UIBezierPaths to the image context. 2) Add a UIImageView as a subview of your view and set the image property with the rendered image. Something like that:

 - (void)viewDidLoad { [super viewDidLoad]; self.imageView = [[UIImageView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:self.imageView]; [self drawPaths]; } - (void)drawPaths { UIGraphicsBeginImageContext(self.view.bounds); //draw... self.imageView.image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } 
0
source share

Swift 3 accepted answer:

 let shape = UIBezierPath(ovalIn: view.bounds) let shapeLayer = CAShapeLayer() shapeLayer.path = shape.cgPath shapeLayer.fillColor = UIColor(red: 0.5, green: 1, blue: 0.5, alpha: 1).cgColor shapeLayer.strokeColor = UIColor.black.cgColor shapeLayer.lineWidth = 2.0 view.layer.addSublayer(shapeLayer) 
0
source share

All Articles