将渐变应用于CAShapeLayer [英] Applying a Gradient to CAShapeLayer
问题描述
有没有人有将Gradient应用于CAShapeLayer的经验? CAShapeLayer是一个很棒的图层类,但它似乎只支持实心填充着色,而我希望它有一个渐变填充(实际上是一个可动画的渐变)。
Does anyone have any experience in applying a Gradient to a CAShapeLayer? CAShapeLayer is a fantastic layer class, but it appears to only support solid fill coloring, whereas I'd like it to have a gradient fill (actually an animatable gradient at that).
其他与CAShapeLayer有关的事情(阴影,形状,笔触颜色,动画形状路径)非常棒。
Everything else to do with CAShapeLayer (shadows, shapes, stroke color, animatable shape path) is fantastic.
我尝试在CAShapeLayer中放置一个CAGradientLayer,或者确实将CAShapeLayer设置为GradientLayer的掩码并将两者都添加到容器层,但这些都没有正确的结果。
I've tried placing a CAGradientLayer inside a CAShapeLayer, or indeed setting the CAShapeLayer as the mask of the GradientLayer and adding both to a container layer, but these don't have the right outcome.
我应该是CAShapeLayer的子类,还是有更好的前进方式?
Should I subclass CAShapeLayer, or is there a better way forward?
谢谢。
推荐答案
您可以使用形状的路径创建遮罩层并将其应用于渐变层,如下所示:
You could use the path of your shape to create a masking layer and apply that on the gradient layer, like this:
UIView *v = [[UIView alloc] initWithFrame:self.window.frame];
CAShapeLayer *gradientMask = [CAShapeLayer layer];
gradientMask.fillColor = [[UIColor clearColor] CGColor];
gradientMask.strokeColor = [[UIColor blackColor] CGColor];
gradientMask.lineWidth = 4;
gradientMask.frame = CGRectMake(0, 0, v.bounds.size.width, v.bounds.size.height);
CGMutablePathRef t = CGPathCreateMutable();
CGPathMoveToPoint(t, NULL, 0, 0);
CGPathAddLineToPoint(t, NULL, v.bounds.size.width, v.bounds.size.height);
gradientMask.path = t;
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.startPoint = CGPointMake(0.5,1.0);
gradientLayer.endPoint = CGPointMake(0.5,0.0);
gradientLayer.frame = CGRectMake(0, 0, v.bounds.size.width, v.bounds.size.height);
NSMutableArray *colors = [NSMutableArray array];
for (int i = 0; i < 10; i++) {
[colors addObject:(id)[[UIColor colorWithHue:(0.1 * i) saturation:1 brightness:.8 alpha:1] CGColor]];
}
gradientLayer.colors = colors;
[gradientLayer setMask:gradientMask];
[v.layer addSublayer:gradientLayer];
如果你还想使用阴影,你必须放置一个重复的形状渐变层下的图层,循环使用相同的路径参考。
If you want to also use the shadows, you would have to place a "duplicate" of the shape layer under the gradient layer, recycling the same path reference.
这篇关于将渐变应用于CAShapeLayer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!