iOS mask view via maskView property

August 24, 2015

iOS mask view via maskView property

Up until now we've all been applying masks trough layers. There was no other way. Starting from now on, from iOS8, iOS mask view has gotten simpler than ever. Now you can achieve same simple mask with regular UIView instance:

CGRect rect = CGRectMake(50, 50, 100, 100);
UIView *mask = [[UIView alloc] initWithFrame:rect];
mask.backgroundColor = UIColor.whiteColor;
mask.layer.cornerRadius = CGRectGetHeight(rect) / 2;
self.view.maskView = mask;

You can even apply layer effects to your mask object and it will work just fine. Just don't forget to set to your mask a color, any color, as long as you have alpha value greater than 0.0.

The view’s alpha channel determines how much of the view’s content and background shows through. Fully or partially opaque pixels allow the underlying content to show through but fully transparent pixels block that content.

So as we've sorted things out with alpha channels, I want to point out one more nice feature, that brings us maskView property: you can also apply masks with UIImageView objects.

Here is how it looks like, when you apply .png image with alpha channels to view:

UIView *view = self.view;
UIColor *color = [UIColor colorWithRed:145.0 / 255.0
                                 green:191.0 / 255.0
                                  blue:192.0 / 255.0
view.backgroundColor = color;

UIImage *star = [UIImage imageNamed:@"Star"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:star];
imageView.frame = view.frame;
imageView.contentMode = UIViewContentModeScaleAspectFit;
view.maskView = imageView;

iOS mask view


comments powered by Disqus