5rpjda
Last Updated: February 25, 2016
·
5.443K
· mystcolor
Avatar 400

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.

Say Thanks
Respond

3 Responses
Add your response

10800
Bb0525f7ad9c008dbb76c7077a2f3096

Very nice little trick!

over 1 year ago ·
10918
826fed780a74ee55eff53d29ea231b90

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 ·
10987
Avatar 400

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 ·
Awesome Job

20838750 ca12 11e7 8395 3d07316c018d
Overijssel,Amsterdam, Arnhem
·
Overijssel, Amsterdam, Arnhem
·
Full Time