CAShapeLayer的渐变色效果 [英] Gradient color effect on CAShapeLayer

查看:2113
本文介绍了CAShapeLayer的渐变色效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在CAShapeLayer上应用渐变色。为此我写代码,

I'm trying to apply gradient colors on CAShapeLayer. For that i write code,

-(void)addCircle{
{
    // Drawing code
    UIBezierPath *aPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(150, 150)
                                                         radius:125
                                                     startAngle:0
                                                       endAngle:DEGREES_TO_RADIANS(180)
                                                      clockwise:NO];


    CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
    [shapeLayer setFrame: self.frame];
    [shapeLayer setPath: [aPath CGPath]];
    shapeLayer.lineWidth = 30.0f;
    [shapeLayer setStrokeColor:[[UIColor redColor] CGColor]];
    shapeLayer.fillColor = [[UIColor clearColor] CGColor];
    [shapeLayer setMasksToBounds:YES];


    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.startPoint = CGPointMake(0.5,1.0);
    gradientLayer.endPoint = CGPointMake(0.5,0.0);
    gradientLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.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:shapeLayer];

    [self.layer addSublayer:shapeLayer];
}

但我没有像这样的渐变色输出,

But i got without gradient color output like this,

我想要这样的最终输出,

I want the final output like this,

但我的主要目标是在CAShapeLayer上应用渐变效果。在我给出的代码中我错了哪里?

But my primarily goal is apply gradient effects on CAShapeLayer. Where i'm wrong in my given code stuff?

推荐答案

主要问题是你要将 shapeLayer 添加到view的图层,但实际上你只想将它用作蒙版,所以你应该添加 gradientLayer

The main problem is that you're adding shapeLayer to the view's layer, but you actually just want to use that as a mask, so you should be adding gradientLayer instead.

下一个问题是 CAGradientLayer 不支持像第二个屏幕截图中那样的径向渐变。你需要做自定义绘图才能达到这个效果(或者只是使用图像)。

The next problem will be that CAGradientLayer doesn't support radial gradients like the one in your second screenshot. You'll need to do custom drawing to achieve that effect (or just use an image).

这篇关于CAShapeLayer的渐变色效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆