ArthurVonBabylon
ArthurVonBabylon

Reputation: 195

Animating a custom CAShapeLayer at a variable rate

I have a series of arcs, all created with code like this and animated with CABasicAnimation @"strokeEnd".

        if (!_fourthShapeLayer) {
            _fourthPath =  [UIBezierPath bezierPathWithArcCenter:CGPointMake(rect.size.width / 2, rect.size.height / 2)
                                                         radius:rect.size.width / 2 - 9.5
                                                     startAngle:startAngle
                                                       endAngle:startAngle - (endAngle - startAngle)
                                                      clockwise:YES];
            _fourthShapeLayer = [CAShapeLayer layer];
            _fourthShapeLayer.path = _fourthPath.CGPath;
            _fourthShapeLayer.fillColor = [UIColor clearColor].CGColor;
            _fourthShapeLayer.strokeColor = [UIColor colorWithHue:.33888889 saturation:.62 brightness:0.62 alpha:1.0].CGColor;
            _fourthShapeLayer.lineWidth = 3.0;
            _fourthShapeLayer.rasterizationScale = 2.0 * [UIScreen mainScreen].scale;
            _fourthShapeLayer.shouldRasterize = YES;
        }

        CABasicAnimation *strokeAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        strokeAnimation.fromValue = [NSNumber numberWithFloat:0.0];
        strokeAnimation.toValue = [NSNumber numberWithFloat:1.0];
        strokeAnimation.duration = 1.0;
        strokeAnimation.speed = 1.0;
        [_fourthShapeLayer addAnimation:strokeAnimation forKey:@"stroke"];

        [self.layer addSublayer:_fourthShapeLayer];

What varies is the color, and the radius when defining the path.

I would like to alter the rate of the arcs' animations to do the following: all start and end at the same time, yet have varying rates. Basically, some arcs start fast and end slow, the others start slow and end fast - all at different rates.

It would be great if I could define the amount of arc drawn like this: pow((elapsedAnimationTime / totalAnimationTime), 1.05) - varying the 'power' (1.05, 1.02, .97, .91 for the different arcs, for instance).

Does anyone have any suggestions? Originally I set a timer and called drawRect: every hundredth of a second, defining the path end points according to the 'power' function mentioned above - but of course this was too costly an operation.

Help appreciated!

Upvotes: 0

Views: 111

Answers (1)

Alex Staravoitau
Alex Staravoitau

Reputation: 2268

You can use a custom timingFunction, e.g.:

animation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.5:0:0.9:0.7];

More on this here: Animations Explained

Upvotes: 2

Related Questions