简体   繁体   English

如何应用CAGradientLayer作为另一个CALayer的掩码?

[英]How to apply CAGradientLayer as mask of another CALayer?

I have a view, which has a CALayer. 我有一个视图,它有一个CALayer。 When I create a CAGradientLayer and apply it as the mask of that view's CALayer, nothing happens. 当我创建一个CAGradientLayer并将其应用为该视图的CALayer的掩码时,没有任何反应。 Why? 为什么?

In -initWithFrame: of the view I do this: 在-initWithFrame:视图中我这样做:

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
//[self.layer insertSublayer:gradient atIndex:0];
self.layer.mask = gradient;

If I replace 如果我更换

self.layer.mask = gradient;

with

[self.layer insertSublayer:gradient atIndex:0];

then I see the gradient. 然后我看到了渐变。 It's from black to white. 它是从黑色到白色。

What's the trick? 有什么诀窍?

The mask property on CALayer uses the alpha component of the mask layer to determine what should be visible and not. CALayer上的mask属性使用遮罩层的alpha分量来确定应该可见的内容而不是。 Since both of your colors (black and white) are fully opaque (no transparency) the mask has no effect. 由于您的两种颜色(黑色和白色)都是完全不透明的(没有透明度),因此蒙版无效。 To fix this you should change one of the colors to a clear color: 要解决此问题,您应该将其中一种颜色更改为清晰的颜色:

gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], 
                                            (id)[[UIColor clearColor] CGColor], nil];

That's the "trick" :D 这就是“诀​​窍”:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM