CAGradientLayer发布使用CAShapeLayer创建的动画圆圈

时间:2015-05-12 12:33:49

标签: ios objective-c core-graphics cashapelayer cagradientlayer

我正在使用UIBezierPath和CAShapeLayer绘制动画圆圈。现在,在添加渐变效果时,出现的问题是 - CAGradientLayer从上下颠倒添加渐变效果。但我想要从圆的起点到圆的终点的渐变效果。

我得到的是 -

enter image description here

我的代码是 - (这是一个函数)

 circle.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(radius+6,radius+6)  radius:radius startAngle:DEGREES_TO_RADIANS(startAngle) endAngle:DEGREES_TO_RADIANS(endAngle) clockwise:isClockWise].CGPath;

    //circle.position = CGPointMake(CGRectGetMidX(self.frame)-radius, CGRectGetMidY(self.frame)-radius);

    circle.fillColor = fillColor.CGColor;
    circle.strokeColor = strokeColor.CGColor;
    circle.lineWidth = lineWidth;
    circle.strokeEnd = percentToDraw/100;
    circle.lineCap = kCALineCapRound;

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.startPoint = CGPointMake(0.5,1.0);
    gradientLayer.endPoint = CGPointMake(0.5,0.0);
    gradientLayer.frame = CGRectMake(0, 0, self.frame.size.width , self.frame.size.height);
    NSMutableArray *colors = [NSMutableArray array];
    [colors addObject:(id)[UIColor blackColor].CGColor];
    [colors addObject:(id)strokeColor.CGColor];

    gradientLayer.colors = colors;
    [gradientLayer setMask:circle];

    [self.layer addSublayer:gradientLayer];

    CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    drawAnimation.duration            = duration;
    drawAnimation.repeatCount         = 1.0;

    drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    drawAnimation.toValue   = [NSNumber numberWithFloat:percentToDraw/100];

    drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

    [circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];

如何添加渐变以使其开始(带红色)并前进到终点(带黑色)。 ?

1 个答案:

答案 0 :(得分:1)

假设您正在讨论圆锥/角度渐变,那么没有系统提供的方法来实现CAGradientLayer。有AngleGradientLayer等库试图提供此功能,但是,与任何第三方解决方案一样,应谨慎使用。

您还可以查看类似于herehere的方法,但是它们会要求您稍微重构一下逻辑。

请注意,此建议仅适用于圆形案例。