Animate a CAShapeLayer to draw a progress circle
Asked Answered
B

2

12

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?

Buckjumper answered 19/2, 2014 at 6:18 Comment(2)
I don't want to use third party code. I want to understand how to do it myself.Buckjumper
"I don't want to use third party code. I want to understand how to do it myself." +1. I feel the same.Nestor
B
6

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];
}
Buckjumper answered 19/2, 2014 at 7:30 Comment(0)
R
1

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

Roundelay answered 22/7, 2014 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.