Core Animation performance on iphone
- by nico
I'm trying to do some animations using Core Animation on the iphone. I'm using CABasicAnimation on CALayer. It's a straight forward animation from a random place at the top of the screen to the bottom of the screen at random speed, I have 30 elements that doing the same animation continuously until another action happens. But the performance on the iPhone 3G is very sluggish when the animations start. The image is only 8k.
Is this the right approach? How should I change so it performs better.
// image cached somewhere else.
CGImageRef imageRef = [[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:@"png"]] CGImage];
- (void)animate:(NSTimer *)timer
{
int startX = round(radom() % 320);
float speed = 1 / round(random() % 100 + 2);
CALayer *layer = [CALayer layer];
layer.name = @"layer";
layer.contents = imageRef; // cached image
layer.frame = CGRectMake(0, 0, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
int width = layer.frame.size.width;
int height = layer.frame.size.height;
layer.frame = CGRectMake(startX, self.view.frame.origin.y, width, height);
[effectLayer addSublayer:layer];
CGPoint start = CGPointMake(startX, 0);
CGPoint end = CGPointMake(startX, self.view.frame.size.height);
float repeatCount = 1e100;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
animation.delegate = self;
animation.fromValue = [NSValue valueWithCGPoint:start];
animation.toValue = [NSValue valueWithCGPoint:end];
animation.duration = speed;
animation.repeatCount = repeatCount;
animation.autoreverses = NO;
animation.removedOnCompletion = YES;
animation.fillMode = kCAFillModeForwards;
[layer addAnimation:animation forKey:@"position"];
}
The animations are fired off using a NSTimer.
animationTimer = [NSTimer timerWithTimeInterval:0.2 target:self selector:@selector(animate:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:animationTimer forMode:NSDefaultRunLoopMode];