Circle crop/mask on views
As soon as we've a square-size frame, we can easily do that using the cornerRadius
provided in CALayer.
// #import <QuartzCore/QuartzCore.h>
view.layer.cornerRadius = CGRectGetWidth(view.frame)/2;
view.layer.maskToBounds = YES;
By setting the cornerRadius
exactly half of the length of the dimensions, we get a perfect circular masked shape.
The beauty of this is the fact that it's a property on CALayer, we can even configure this in Interface Builder with zero lines of code:
Add
layer.cornerRadius
to User Runtime Attributes
Make sure Clip Subviews is checked
And there you'll get the same result in runtime. :) It's that simple trick I learnt from [here][].
[here]:https://medium.com/unforgettable-moments/3db44088db70
Written by James Tang
Related protips
3 Responses
Very nice little trick!
Could this have performance issues? Setting a view's cornerRadius property is not as performant as drawing a circle with CoreGraphics. You could easily create a UIView subclass where the drawRect: method just draws a circle of radius self.bounds.size.width / 2.0; and just have an invariant that the view's width and height are equal. Corner radius is obviously much easier though.
Apple engineers does mention about performance on CALayer.cornerRadius, it's much faster on iOS 6, but yes it's still slow.
On other hand, -[UIView drawRect:] consumes CPU process, it's not as performant on retina devices. Technical wise, you'll also need to subclass your UIView, and in case you want to support different contentMode there'll be more work than expected.
Obviously there are several ways to circle masks. I'd consider this is good and simple enough for general use, and the beauty of this is developers will be able to define it in User Defined Runtime Attributes, that means you need to write zero lines of code when you're using IB to prototype your app, see the updated the post :)