使用CALayers添加遮罩 [英] Adding a mask with CALayers
问题描述
我似乎很难通过CALayers添加面具。我只是试图掩盖UIImageView。这是我的代码:
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为黑色,透明圆圈穿过它(这是掩盖的正确方法吗?) 。我不知道这个失败的地方,也许在 maskLayer.contents
因为它应该是 CGImageRef
但是我当我将其设置为 mask.CGImage
时,或通过局部变量 CGImageRef = mask.CGImage
时出现错误。无论如何,它的设置现在不会出错,所以我希望它没问题。
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.
有谁知道发生了什么,或者如何正确设置CALayers的面具?谢谢
Does anyone know what's going on, or how to properly set masks with CALayers? Thanks
推荐答案
尝试
maskLayer.contents = (id)mask.CGImage;
是的,演员很糟糕,但这是必要的。
Yes, the cast sucks, but it's necessary.
我想你还需要说
maskLayer.bounds = (CGRect){CGPointZero, mask.size};
这篇关于使用CALayers添加遮罩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!