Search code examples
iphoneioscore-animationcabasicanimation

Animating Circle's endAngle with CABasicAnimation


I have some UIView with drawrect code for drawing pie:

    - (void)drawRect:(CGRect)rect
    {
        CGRect parentViewBounds = self.bounds;
        CGFloat x = CGRectGetWidth(parentViewBounds)/2;
        CGFloat y = CGRectGetHeight(parentViewBounds)/2;

        // Get the graphics context and clear it
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextClearRect(ctx, rect);


        // define line width
        CGContextSetLineWidth(ctx, 4.0);


        CGContextSetFillColor(ctx, CGColorGetComponents( [someColor CGColor]));
        CGContextMoveToPoint(ctx, x, y);
        CGContextAddArc(ctx, x, y, 100,  radians(270), radians(270), 0); // 27
        CGContextClosePath(ctx);
        CGContextFillPath(ctx);
}

But when I try to animate "endAngle" property after drawing, it doesn't work:

CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"endAngle"];
theAnimation.duration=1;
theAnimation.repeatCount=1;
theAnimation.autoreverses=NO;
theAnimation.fromValue=[NSNumber numberWithFloat:270];
theAnimation.toValue=[NSNumber numberWithFloat:60];
[[self.layer presentationLayer] addAnimation:theAnimation forKey:@"animateLayer"];

Where I'm making a mistake?


Solution

  • If you want to make an animation then you should look into using Core Animation for the drawing. It makes animation much simpler.

    Have a look at this great tutorial on making a custom animatable pie chart with Core Animation. I'm sure that you can modify it to get what you want.

    If it seems to complicated to you then you can have a look at my answer to "Draw part of a circle" which draws a pie chart shape by making a very wide stroke of a circle.