Animating the frame of a CALayer.

Q: When I try to animate the frame of a CALayer nothing happens. Why?

A: The frame property of a CALayer is a derived property, dependent on the position, anchorPoint, bounds and transform of the layer. Instead of animating the frame, you should instead animate the position or bounds, depending on what effect you are trying to accomplish.

To move a layer, you can animate the position as shown in Listing 1.

Listing 1: Animating position.

-(void)moveLayer:(CALayer*)layer to:(CGPoint)point
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.toValue = [NSValue valueWithPoint:NSPointFromCGPoint(point)];
    [layer addAnimation:animation forKey:nil];
    layer.position = point;
}

To resize a layer, you would animate the bounds.size parameter as shown in Listing 2.

Listing 2: Animating size.

-(void)resizeLayer:(CALayer*)layer to:(CGSize)size
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"bounds.size"];
    NSValue *value = [NSValue valueWithSize:NSSizeFromCGSize(size)];
    animation.toValue = value;
    [layer addAnimation:animation forKey:nil];
    [layer setValue:value forKeyPath:@"bounds.size"];
}

Note: Both of the listings above also set the value of the position or bound.size so that when the animation completes the layer retains that new value. If this is not desired, for example for a type of "pop" animation where you want the layer to temporarily grow larger, then you only need to add the animation to the layer and not set the new value.

You can combine these animations using a CAAnimationGroup if you need to move and resize a layer at the same time. For more information you will want to read the Core Animation Programming Guide, specifically the sections on Layer Geometry and Transforms , Animation, and Core Animation Extensions To Key-Value Coding as well as the appropriate reference documents. Finally, the Core Animation Cookbook offers sample code for common tasks that you can drop directly into your application.

Document Revision History

Date Notes
2008-10-24 First Version

Posted: 2008-10-24


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.