iphone - 在 iOS 上,为什么更改 CALayer 的帧不会导致动画?

标签 iphone ios core-animation

我有一些 iOS 示例代码,如果我点击主视图并且点击处理程序更改 CALayer对象的frame属性,图层对象将根据其位置和大小进行动画处理。

但是如果我把那个动画放在 ViewControllerviewDidLoad :

UIImage *shipImage = [UIImage imageNamed:@"SpaceShip1.png"];
ship1 = [[CALayer alloc] init];

ship1.contents = (id) [shipImage CGImage];
ship1.frame = CGRectMake(50, 50, 100, 100);

[self.view.layer addSublayer:ship1];

ship1.frame = CGRectMake(0, 0, 300, 200);

那么动画就不会发生。它只会使用 (0, 0, 300, 200)没有动画。为什么会这样以及如何使其发挥作用?

最佳答案

几件事。

首先,frame 属性是不可动画的。相反,您应该为边界(以更改大小)和位置(以移动图层)设置动画。

引用文档:

Note: The frame property is not directly animatable. Instead you should animate the appropriate combination of the bounds, anchorPoint and position properties to achieve the desired result.



其次,在更改动画属性之前,您必须在添加图层后返回事件循环。

当您返回并且系统访问事件循环时,下次您更改可动画属性时,它会创建一个动画事务来为该更改设置动画。

由于您创建了一个图层,设置了它的框架,然后更改了它,所有这些都在返回之前,您的代码只是在它的最后一帧添加了图层。

相反,您应该做的是设置图层,将其安装到其父图层中,然后返回。您可以使用 performSelector:withObject:afterDelay: 在添加图层后调用动画:
- (void)viewDidLoad
{
  UIImage *shipImage = [UIImage imageNamed:@"SpaceShip1.png"];
  ship1 = [[CALayer alloc] init];

  ship1.contents = (id) [shipImage CGImage];
  ship1.frame = CGRectMake(50, 50, 100, 100);

  [self.view.layer addSublayer:ship1];

  [self performSelector: @selector(changeLayer)
    withObject: nil 
    afterDelay: 0.0];
}


- (void) changeLayer
{
  //Animate changes to bounds and position, not frame.
  ship1.bounds = CGRectMake(0, 0, 300, 200);
  //Note that position is based on the center of the layer by default, so you'll 
  //need to adjust your desired position.
  ship1.position = CGPointMake(0,0);
}

关于iphone - 在 iOS 上,为什么更改 CALayer 的帧不会导致动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10368700/

相关文章:

macos - 来自 CA_DEBUG_TRANSACTIONS 的更长回溯

ios - 无法弄清楚雅虎天气应用程序中使用的 uiview 转换

iphone - 调试 iOS 异常的好方法

iphone - 如何获得iphone加速度计的采样率频率?

objective-c - 将文本字段中的用户输入存储到 NSArray 中

iphone - 手动淡入新添加的 subview ?

ios - 为什么 CALayer 不维护其内容?

ios - 我没有 iPhone5,想在同一版本上测试功能以进行构建,我该怎么做?

ios - 如何使用Out @State 变量更新 SwiftUIView?和段错误问题

ios - UIView 在其 Superview 内部移动