旋转动画重置为原始图像

Spin Animation Resets to Original Image

为了好玩,我一直在尝试使用 objective c 中的 Xcode 设置一个彩票轮类型的对象。到目前为止,我已经能够成功地随机旋转对象,并在轮子上的 8 个项目中的 1 个处停止。

问题是,我不确定如何 "save" 旋转的动画层。每次我旋转轮子时,一旦动画完成,它就会重置并以原始方向显示图像。下面是我为旋转轮子设置的代码。 (注意:在这段代码中,我只是设置了一个旋转。这是我正在使用的模板,用于尝试保留图像。其他代码位于另一个项目中,用于存储停止点并对其进行更正到其中一个对象的中心。)

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

#define SPIN_CLOCK_WISE 1
#define SPIN_COUNTERCLOCK_WISE -1

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)spinButton:(id)sender {
    [self spinLayer:_spinImage.layer duration:10 direction:SPIN_CLOCK_WISE];

}


- (void)spinLayer:(CALayer *)inLayer duration:(CFTimeInterval)inDuration
        direction:(int)direction
{
    CABasicAnimation* rotationAnimation;

    // Rotate about the z axis
    rotationAnimation =
    [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];

    // Rotate 360 degress, in direction specified
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 22.3 * direction];

    // Perform the rotation over this many seconds
    rotationAnimation.duration = inDuration;

    // Set the pacing of the animation
    rotationAnimation.timingFunction =
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    // Add animation to the layer and make it so
    [inLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

    // Save animation
//%%%%%%%%%%  THIS IS WHERE I AM STUCK!! %%%%%%%%%
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

如果有人能帮我保留旋转的图像,以便在 spinLayer 方法完成后,图像保持旋转到新的旋转方向,我将不胜感激。谢谢!

令人困惑的部分是动画只是改变图层的外观,而不是图层的属性。

您可以将动画视为在渲染时覆盖 属性。

如您所见,由于模型值从未改变,当动画完成并自行移除时,图层会返回渲染该 属性 的实际值。

解决这个问题的错误方法是让动画永远存在。它确实产生了正确的渲染,但有一些不需要的副作用,因为模型值现在 "permanently" 与外观不匹配。

相反,更好的解决方案是在将动画添加到图层时更新正在设置动画的 属性 的值。这可能会破坏动画,但如果动画是从旧值到新值的动画,它会 "override" 无论模型值是什么原因渲染,当动画移除时,最终值将匹配模型值。


有关添加动画时在何处更改模型值以及应用动画的方式的更深入讨论,请参阅 this question and this blog post of mine