Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate a CAShapeLayer to draw a progress circle

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?

like image 674
Nic Hubbard Avatar asked Feb 19 '14 06:02

Nic Hubbard


2 Answers

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];
}
like image 121
Nic Hubbard Avatar answered Nov 03 '22 17:11

Nic Hubbard


My answer with example here. In general you should add the animation to CAShapeLayer.

like image 20
Darkngs Avatar answered Nov 03 '22 16:11

Darkngs