13

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

user339946
  • 5,961
  • 9
  • 52
  • 97

2 Answers2

22

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};
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • Hey, thanks for your help on the original question, I was trying to follow through with your suggestions. Anyhow, that doesn't seem to do the trick either. I don't see any masks or my viewToMask for that matter. – user339946 Mar 07 '12 at 03:56
  • @user339946: You probably need to define the `bounds` of `maskLayer`. – Lily Ballard Mar 07 '12 at 04:25
  • Frame worked well for me too. Love how little code is required to apply a mask... brilliant. Thanks everyone. – Jesse Head Jul 22 '14 at 13:24
13

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

Hector
  • 3,909
  • 2
  • 30
  • 46