user3693546
user3693546

Reputation:

CAGradientLayer issues for animated circle created using CAShapeLayer

I am drawing an animated circle using the UIBezierPath and CAShapeLayer. Now while adding the gradient effect the problem occurring is - CAGradientLayer adds it's gradient effect from upside down. But I want gradient effect from the starting point of the circle to the end point of the circle.

What I am getting is -

enter image description here

My code is - (it's a function)

 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"];

How do I add gradient so that it starts(with red) and goes forward to finish point(with black). ?

Upvotes: 1

Views: 1861

Answers (1)

Henri Normak
Henri Normak

Reputation: 4725

Assuming you are talking about a conical/angle gradient, then there is no system provided method for achieving that with CAGradientLayer. There are libraries such as AngleGradientLayer that try to provide this functionality, however, as with any 3rd party solution, it should be used with caution.

You can also look at approaches like ones discussed here or here, however they would require you to slightly refactor your logic.

Note that this suggestions would only work in a circular case.

Upvotes: 1

Related Questions