Why ever use `keyTimes`, `timingFunctions` or `timingFunction` on CAKeyframeAnimation?

491 views Asked by At

Interpolating the values with a custom function is very easy. But is it bad practice? Should I instead (or in addition) use keyTimes, timingFunctions or timingFunction to explain the animation-curve to the framework? When working with custom animation curves I really don't see why I should use those properties. I want to do this right.

This works just fine. As expected it animates the views-position with a custom cubic-ease-out animation curve:

CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"position.x"];
anim.duration = 5;
NSUInteger numberOfFrames = anim.duration * 60;

NSMutableArray *values = [NSMutableArray new];

for (int i = 0; i < numberOfFrames; i++)
{
    CGFloat linearProgress = (double) i / (double) numberOfFrames;
    CGPoint position = view.layer.position;
    position.x = 10 + (300 * CubicEaseOut(linearProgress));
    [values addObject:[NSValue valueWithCGPoint:position]];
}

anim.values = values;

[view.layer addAnimation:anim forKey:@"position"];
1

There are 1 answers

1
jsh On BEST ANSWER

Your method adds 300 keyframes to the animation, for Core Animation to interpolate, linearly. There are two reasons this might not be worse than using fewer keyframes with non-linear interpolation to to get the same result: (1) more data to send to CA, i.e. more data to store and read every animation frame; (2) if you ever wanted to slow down the animation so that more than 300 frames are rendered from it the linear interpolation artifacts may become visible.

If you just have one 3s animation, it's likely neither of those reasons are important, but e.g. if you had 100 10s animations all running at once you may see worse performance than if using fewer keyframes.