Animate a CAShapeLayer to draw a progress circle

Nic Hubbard picture Nic Hubbard · Feb 19, 2014 · Viewed 13.9k times · Source

I am trying to draw a circle that will be used to indicate progress. The progress updates might come in quickly, and I want to animate the changes to the circle.

I have tried doing this with the below methods, but nothing seems to work. Is this possible?

- (id)initWithFrame:(CGRect)frame strokeWidth:(CGFloat)strokeWidth insets:(UIEdgeInsets)insets
{
    if (self = [super initWithFrame:frame])
    {

        self.strokeWidth = strokeWidth;

        CGPoint arcCenter = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
        CGFloat radius = CGRectGetMidX(self.bounds) - insets.top - insets.bottom;

        self.circlePath = [UIBezierPath bezierPathWithArcCenter:arcCenter
                                                         radius:radius
                                                     startAngle:M_PI
                                                       endAngle:-M_PI
                                                      clockwise:YES];
        [self addLayer];
    }
    return self;
}


- (void)setProgress:(double)progress {
    _progress = progress;
    [self updateAnimations];
}

- (void)addLayer {

    CAShapeLayer *progressLayer = [CAShapeLayer layer];
    progressLayer.path = self.circlePath.CGPath;
    progressLayer.strokeColor = [[UIColor whiteColor] CGColor];
    progressLayer.fillColor = [[UIColor clearColor] CGColor];
    progressLayer.lineWidth = self.strokeWidth;
    progressLayer.strokeStart = 10.0f;
    progressLayer.strokeEnd = 40.0f;

    [self.layer addSublayer:progressLayer];
    self.currentProgressLayer = progressLayer;

}

- (void)updateAnimations{

    self.currentProgressLayer.strokeEnd = self.progress;
    [self.currentProgressLayer didChangeValueForKey:@"endValue"];
}

Currently this code doesn't even draw the circle, but removing the progressLayer's strokeStart and strokeEnd will draw the full circle.

How can I get it to begin at a certain point and start drawing the circle based on me setting my progress property?

Answer

Nic Hubbard picture Nic Hubbard · Feb 19, 2014

I figured it out. The strokeStart and strokeEnd values are from 0.0 to 1.0, so the values I was giving it were way too high.

So, I just updated my setting to:

- (void)setProgress:(double)progress {
    _progress = progress * 0.00460;
    [self updateAnimations];
}