Tuesday, April 12, 2011

Animating a series of images with CALayer

So you want a to animate a series of images, flip book style. While it is true you can use UIImageView, everyone knows that is for wimps. Real men (& ladies ;) ) use CALayer (like a boss)...

But how? Well you might have some how got in your head that CALayer's contents property supports a NSArray of CGImages. Well this is not the answer, remember that the contents property takes an 'id'as a argument so it supports virtually everything under the sun and then some. Hell, if you felt like making crazy things happen you could just throw a NSData object in there.

Anyways, the actual solution is to use a CAKeyFrameAnimation, to manage the rotation of your images, control the frame rate, and ultimately the duration.

Well all is said and done it should look at this

//Create the layer
layer = [CALayer layer];
//Configure the animation
animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
[animation setCalculationMode:kCAAnimationDiscrete];
[animation setDuration:2.0f];
[animation setRepeatCount:HUGE_VALF];
[animation setValues:/* your NSArray of CGImageRefs*/];
//Add the animation to the layer
[layer addAnimation:animation
forKey:@"contents"
];
[layer setFrame:/* The frame of the layer*/];
//Add to the super layer
[parentLayer addSublayer:layer];
view raw CALayer.m hosted with ❤ by GitHub

No comments: