用 CAShapeLayer 实现绘制渐变圆弧

Implement drawing gradient arc with CAShapeLayer

参考发现的已接受答案 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 方法是理想的。

问题 1:您的图层没有框架。添加:

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

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

[self.view.layer addSublayer:circleLayer];

改为这样说:

[self.view.layer addSublayer:gradientLayer];

结果: