Wednesday, June 12, 2013

CAAnimation setTimingFunction example in Objective C (iOS).

CAAnimation setTimingFunction

An optional timing function defining the pacing of the animation.

@property(retain) CAMediaTimingFunction *timingFunction

Discussion of [CAAnimation setTimingFunction]
Defaults to nil, indicating linear pacing.

CAAnimation setTimingFunction example.
When animating the movement of a UIView within a begin / commit animation block, you can use the following method to set the animation timing curve:

[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
When animating a layer via CAAnimation, you can use the following to set the timing function there:

[animation setTimingFunction:kCAMediaTimingFunctionEaseInEaseOut];
Finally, when wrapping a series of animations in a CATransaction, you can use the following to set the coordinated timing function of all the animations:

[CATransaction setAnimationTimingFunction:kCAMediaTimingFunctionEaseInEaseOut];

Example of [CAAnimation setTimingFunction].
-(void)animateCounterMoveFor:(int)playerType counterId:(int)countId {

    // set up the move to an end point
    CABasicAnimation *move = [CABasicAnimation animationWithKeyPath:@"position"];
    [move setDuration:3.5];
    [move setToValue:[NSValue valueWithCGPoint:CGPointMake((xPos), (yPos))]];
    [move setFillMode:kCAFillModeForwards];
    [move setRemovedOnCompletion:NO];
    CAMediaTimingFunction *tf = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [move setTimingFunction:tf];

    [layer addAnimation:move forKey:@"position"];   // Replaces the previous position animation on the layer
    [layer setPosition:CGPointMake(xPos, yPos)];        // Sets the final position after animation is finished

    // enable the animation stop to set layer to right position
    [move setValue:[NSNumber numberWithInt:countId] forKey:@"counterId"];
    [move setValue:[NSNumber numberWithInt:playerType] forKey:@"playerType"];
    [move setDelegate:self];

}

CAAnimation setTimingFunction example.
[myLayer addAnimation:frameAnimation forKey:@"frame"];
You may also set an action to the layer to make all frame changes animated with your animation:

CABasicAnimation *frameAnimation = [CABasicAnimation animation];
frameAnimation.duration = 2.5;
frameAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

myLayer.actions = [NSDictionary dictionaryWithObjectsAndKeys:frameAnimation, @"frame", nil];

End of CAAnimation setTimingFunction example article.