Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mask UIViews in iOS

Tags:

ios

uiview

mask

I've seen similar questions, but haven't found workable answers.

I want to mask a UIView using a grey image (need to convert to alpha scale for masking). The UIView has background. It should be easy to mask an image, but I want to mask any UIView.

Any clues will be appreciated.

like image 241
subchap Avatar asked Dec 30 '10 03:12

subchap


People also ask

What is layer Swift?

Overview. Layers are often used to provide the backing store for views but can also be used without a view to display content. A layer's main job is to manage the visual content that you provide but the layer itself has visual attributes that can be set, such as a background color, border, and shadow.


1 Answers

I've been working on this problem for a couple of hours and have a solution that I think will do what you want. First, create your masking image using whatever means you see fit. Note that we only need the alpha values here, all other colours will be ignored, so make certain that the method you use supports alpha values. In this example I'm loading from a .png file, but don't try it with .jpg files as they don't have alpha values.

Next, create a new layer, assign your mask to its contents and set this new layer to your UIView's own layer, like so: you should find that this masks the UIView and all its attached subviews:

UIImage *_maskingImage = [UIImage imageNamed:@"mask"]; CALayer *_maskingLayer = [CALayer layer]; _maskingLayer.frame = theView.bounds; [_maskingLayer setContents:(id)[_maskingImage CGImage]]; [theView.layer setMask:_maskingLayer]; 

With this done, you can set the UIView's background colour to whatever you like and the mask will be used to create a coloured filter.

EDIT: As of iOS8 you can now mask a view simply by assigning another view to its maskView property. The general rules stay the same in that the maskView's alpha layer is used to determine the opacity of the view it is applied to.

like image 69
Ash Avatar answered Oct 04 '22 06:10

Ash