使用CAShapeLayer实现绘制渐变弧

时间:2015-12-23 16:26:01

标签: ios objective-c uiview cashapelayer cagradientlayer

参考已接受的答案here我尝试实施此问题并遇到CAShapeLayer路径问题我的代码如下:

-(void)drawGradientArc{
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];

    CAShapeLayer *circleLayer = [CAShapeLayer new];
    circleLayer.lineWidth = 25;
    circleLayer.fillColor = [UIColor clearColor].CGColor;
    circleLayer.strokeColor = [UIColor redColor].CGColor;

    CGFloat radius = 150;


    [bezierPath addArcWithCenter:self.view.center radius:radius startAngle:0 endAngle:M_PI clockwise:YES];


    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.startPoint = CGPointMake(0,0);
    gradientLayer.endPoint = CGPointMake(1,0);


    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:circleLayer];

    circleLayer.path = bezierPath.CGPath;

    [self.view.layer addSublayer:circleLayer];
}

这将正确绘制半圆弧,但渐变的路径未正确设置,我无法拼凑出如何使用渐变来准确配置代码。有一个CGPathCreateCopyByStrokingPath我认为我可能还需要调用以正确设置渐变的路径,但不太确定如何。任何有关如何构建代码以使其工作的帮助将不胜感激。我还包括了我试图重现的渐变图像。 CAShapeLayerCAGradientLayer方法是理想的。

enter image description here

1 个答案:

答案 0 :(得分:4)

问题1 :您的图层没有框架。加上这个:

gradientLayer.frame = self.view.layer.bounds;
circleLayer.frame = gradientLayer.bounds;

问题2 :您正在向视图的图层添加错误的图层。你在哪里:

[self.view.layer addSublayer:circleLayer];

这样说:

[self.view.layer addSublayer:gradientLayer];

<强>结果

enter image description here