Last Updated: December 26, 2018
·
6.965K
· mystcolor

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:

  1. Add layer.cornerRadius to User Runtime Attributes
    Picture

  2. Make sure Clip Subviews is checked
    Picture

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

3 Responses
Add your response

Very nice little trick!

over 1 year ago ·

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.

over 1 year ago ·

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 :)

over 1 year ago ·