Gradient color effect on CAShapeLayer

眉间皱痕 提交于 2019-12-10 21:06:46

问题


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,

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


回答1:


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.

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



来源:https://stackoverflow.com/questions/15805897/gradient-color-effect-on-cashapelayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!