Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a mask with CALayers

I seem to be having difficulties adding a mask via CALayers. I'm simply trying to mask a UIImageView. Here's my code:

 CALayer *maskLayer = [CALayer layer];
 UIImage *mask = [UIImage imageNamed:@"mask.png"];
 maskLayer.contents = mask;

UIImageView *viewToMask = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
viewToMask.image = [UIImage imageNamed:@"picture.png"];
viewToMask.layer.mask = maskLayer;
[self.view addSubview:viewToMask];

Mask.png is black with a transparent circle punched through it (is this correct way to mask?). I'm not sure where this is failing, perhaps at maskLayer.contents since its supposed to be a CGImageRef but I get errors when I set it as mask.CGImage, or through a local variable CGImageRef = mask.CGImage. Anyway, the way its set now doesn't give errors, so I hope its fine.

Does anyone know what's going on, or how to properly set masks with CALayers? Thanks

like image 363
user339946 Avatar asked Mar 07 '12 03:03

user339946


People also ask

What is mask in CALayer?

CALayer has a property called mask . The mask property is also a CALayer. It has all the same drawing and layout properties of any other layer. Mask layer located relative to its parent. It is used in a similar way to a sublayer, but it does not appear as a normal sublayer.

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.


2 Answers

Try

maskLayer.contents = (id)mask.CGImage;

Yes, the cast sucks, but it's necessary.


I think you'll also need to say

maskLayer.bounds = (CGRect){CGPointZero, mask.size};
like image 191
Lily Ballard Avatar answered Oct 06 '22 05:10

Lily Ballard


try this:

CALayer *maskLayer = [CALayer layer];
UIImage *mask = [UIImage imageNamed:@"mask.png"];
maskLayer.contents = (id)mask.CGImage;
//  maskLayer.contentsGravity = kCAGravityCenter;
maskLayer.frame = CGRectMake(0.0, 0.0,1024,768);

UIImageView *viewToMask = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];
viewToMask.image = [UIImage imageNamed:@"picture.png"];
viewToMask.layer.mask = maskLayer;
[self.view addSubview:viewToMask];

you also need to set mask frame

like image 30
Hector Avatar answered Oct 06 '22 06:10

Hector