Reputation: 915
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?
Upvotes: 8
Views: 7016
Reputation: 122
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)
Upvotes: 2
Reputation: 3251
Swift 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)
Upvotes: 8
Reputation: 104082
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];
Upvotes: 19
Reputation: 2044
You could: 1) render UIBezierPaths into image context. 2) Add UIImageView as a subview of your view and set image property with rendered image. Something like this:
- (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();
}
Upvotes: 0