【问题标题】:CABasicAnimation how to make it easyCABasicAnimation 如何让它变得简单
【发布时间】:2012-05-14 21:25:54
【问题描述】:

我目前在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"];

但是,当像上面那样对 ~3 个单元格进行动画处理时,动画会变得非常滞后。有什么办法可以减少这种延迟?

【问题讨论】:

  • 我不认为在单元格内设置动画是一个好主意,我发现当表格滚动时,使用 CADisplayLink 的东西会暂停(可能是别的东西)。也许您可以尝试仅对活动单元格或类似的东西进行动画处理。
  • 在我的情况下,我不知道哪些单元格将带有动画。所以硬编码/统计不是最好的变体...
  • 您正在旋转的图像有多大?图层还应用了哪些其他属性?使用小图像,我没有注意到我的 iPhone 4 有延迟。

标签: iphone objective-c ios core-animation cabasicanimation


【解决方案1】:

我要做的第一件事是将动画创建代码从-tableView:cellForRowAtIndexPath: 方法中删除到(比如说)viewDidLoad。然后在-tableView:cellForRowAtIndexPath: 方法中将动画添加到单元格中。

对象创建和矩阵计算代价高昂,因此每次调用-tableView:cellForRowAtIndexPath: 都会降低代码速度。

在代码中,我会有类似以下的内容:

- (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;
}

这样可以吗?

【讨论】:

  • 你测试过这个吗?应用崩溃。
  • 是的:你需要像这样保留rotationAnimation 对象:rotationAnimation = [[CABasicAnimation animationWithKeyPath:@"transform"] retain];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-10
  • 1970-01-01
  • 2014-03-06
  • 1970-01-01
  • 1970-01-01
  • 2011-05-14
相关资源
最近更新 更多