简体   繁体   中英

How to apply CAGradientLayer as mask of another CALayer?

I have a view, which has a CALayer. When I create a CAGradientLayer and apply it as the mask of that view's CALayer, nothing happens. Why?

In -initWithFrame: of the view I do this:

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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