Masking views

Ilter Cengiz
Objective Tidbits
Published in
2 min readDec 16, 2016

Apart from `cornerRadius`, we can easily mask any view with any shape and path using `UIBezierPath` and `CAShapeLayer`. This provides us much more flexibility in laying out our subviews and making them as odd as possible.

Rounding corners

Any views’ corners can be rounded like so;

view.layer.cornerRadius = 8.0

But, what if we wanted to round only two corners and let the other corners be squared? At this point `UIBezierPath` and `CAShapeLayer` come to the rescue!

First we need to create the path of our mask with the desired corners rounded.

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.titleLabel.bounds                                               byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight                                                     cornerRadii:CGSizeMake(8.0, 8.0)];

Then we create the shape layer object with an adjusted frame to be set as mask layer of our view.

CAShapeLayer *maskLayer = [CAShapeLayer new];maskLayer.frame = self.titleLabel.bounds;

At this point, the only thing we need to do is to set the path of our mask layer.

maskLayer.path = maskPath.CGPath;

Being a Core Animation framework class, `CAShapeLayer`’s `path` takes a `CGPath`.

Now we have our mask to be applied. The only task left is to apply it! It’s done so:

self.view.layer.mask = maskLayer;

We have a brand new view whose top left and top right corners are rounded with a radius of `8.0`.

Star

We want to our image view to be masked with a star. First create the star shaped bezier path, like so:

I used PaintCode to create this bezier path. You can find the paint code drawing file here.

UIBezierPath* starPath = UIBezierPath.bezierPath; [starPath moveToPoint: CGPointMake(128, 0)];[starPath addLineToPoint: CGPointMake(156.58, 88.66)];[starPath addLineToPoint: CGPointMake(249.74, 88.45)];[starPath addLineToPoint: CGPointMake(174.24, 143.03)];[starPath addLineToPoint: CGPointMake(203.24, 231.55)];[starPath addLineToPoint: CGPointMake(128, 176.62)];[starPath addLineToPoint: CGPointMake(52.76, 231.55)];[starPath addLineToPoint: CGPointMake(81.76, 143.03)];[starPath addLineToPoint: CGPointMake(6.26, 88.45)];[starPath addLineToPoint: CGPointMake(99.42, 88.66)];[starPath closePath];

Also, I assumed that `imageView` is 256x256 points in size.

Then, create the layer and set its path:

CAShapeLayer *starShape = [CAShapeLayer new];starShape.frame = imageView.bounds;    starShape.path = starPath.CGPath;

And finally set `imageView`’s mask layer:

imageView.layer.mask = starShape;

The result is:

You can find the gist of the content above here.

--

--

Ilter Cengiz
Objective Tidbits

iOS developer at Careem. Writes at @objtidbits. Hobbyist photographer. Pokémon master, Nintendo addict.