我有一些 iOS 示例代码,如果我点击主视图并且点击处理程序更改 CALayer
对象的frame
属性,图层对象将根据其位置和大小进行动画处理。
但是如果我把那个动画放在 ViewController
的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];
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/