Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CABasicAnimation how to make it easy

I'm currently using the following animation on a UITableViewCell:

CATransform3D rotationTransform = CATransform3DMakeRotation(1.0f * M_PI, 0, 0, 1.0);
CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];

rotationAnimation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
rotationAnimation.duration = 0.25f;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = 1;

[cell.rotatingImage.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

However, when ~3 cells are animated as above the animations become very laggy. Is there any way I can reduce this lag?

like image 546
LightNight Avatar asked May 14 '12 21:05

LightNight


1 Answers

The first things that I would is remove the animation creation code from the -tableView:cellForRowAtIndexPath: method to (say) the viewDidLoad. Then add the animation to the cell in the -tableView:cellForRowAtIndexPath: method.

Object creation and matrix calculations are expensive, so doing them for each call to the -tableView:cellForRowAtIndexPath: is going to slow down your code.

In code, I'd have something similar to the following:

- (void) viewDidLoad 
{
    // Normal viewDidLoad code above
    ...

    // Assume that rotationAnimation is an instance variable of type CABasicAnimation*;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];

    CATransform3D rotationTransform = CATransform3DMakeRotation(1.0f * M_PI, 0, 0, 1.0);

    rotationAnimation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
    rotationAnimation.duration = 0.25f;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // create cell
    ...
    // Now apply the animation to the necessary layer.
    [cell.rotatingImage.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

    return cell;
}

Does this do it?

like image 122
haroldcampbell Avatar answered Oct 15 '22 08:10

haroldcampbell