Search code examples
iphoneiosobjective-ccore-animationcabasicanimation

struggle to understand toValue, byValue of CABasicAnimation, ios


I am learning a different way to create a custom indicator. Below is a partial code from tutorial using CABasicAnimation to achieve a task.

-(void)spin
{
    CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    spinAnimation.toValue           = [NSNumber numberWithFloat:2*M_PI];
    spinAnimation.duration          = self.animationDuration;
    spinAnimation.delegate          = self;
    [self.layer addAnimation:spinAnimation forKey:@"spinAnimation"];
}

What is the toValue at line number 2 and what it is used for. When I tried to use

spinAnimation.byValue = [NSNumber numberWithFloat:2*M_PI];

I dont get the idea of these interpolation values.Was searching over the internet but cant still get the whole picture of it.. Please help if you have any ideas about it. All comments are appreciated.


Solution

  • CABasicAnimations can be a little tough to wrap your head around, but the properties associated with the animation really aren't that tough, once you can visualize what they're trying to accomplish. For instance, if I have a red square that represents a layer, and I want to rotate it 360˚ (as you're doing there), then I have to initialize an animation object, tell it what I want to animate, and where I want the animation to go.

    The animation you've provided mutates a CALayer's internal matrix so that it is rotated to a given value (in this case, 2 * M_PI, or 360˚) from it's current position (because you haven't specified a fromValue) over the given duration. A given by value tells the animation that over the given period of time, you want the animation to interpolate (or move) by the given value for the provided duration (for instance, you could chunk the animation into 45˚ "blocks" by specifying a byValue of @(M_PI/2)). The default byValue is a division of the difference of the toValue and fromValue over the duration of the animation such that the animation is smooth and continuous.

    enter image description here

    So, you can think about the animation as going from the layer's initial rotational value, to the layer's new rotational value, by interpolating a given amount or value for a period of time.