使用CABasicAnimation停止旋转图像

Wes*_*ick 2 objective-c ios

UIImageView使用以下代码进行旋转:

CABasicAnimation *rotation;
rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
rotation.fromValue = [NSNumber numberWithFloat:0];
rotation.toValue = [NSNumber numberWithFloat:(2*M_PI)];
rotation.duration = 2.0;
rotation.repeatCount = HUGE_VALF;
[myView.layer addAnimation:rotation forKey:@"Spin"];
Run Code Online (Sandbox Code Playgroud)

我可以通过跑步来阻止它

[myView.layer removeAnimationForKey:@"Spin"];
Run Code Online (Sandbox Code Playgroud)

但是,当动画停止时,图像会重置到它开始的位置.如果图像处于转弯中,这看起来有点尴尬,所以我希望它能够准确地停止它在旋转中的位置.我假设这需要在停止动画之前获取当前旋转量,然后在停止动画后立即将其设置回该旋转量.我不知道怎么做.

Mic*_*lum 6

有几种方法可以做到这一点.一种方法是我影响图层速度属性,你可以在这篇文章的答案中找到一个例子:有没有办法暂停CABasicAnimation?.但这种方式更像是暂停动画的手段.

由于你想要停止它,我建议你继续调用removeAnimationForKey:就像你一样,并将它与CATransform3D耦合,使其与视图的presentationLayer变换相匹配,然后停止动画.试试看:

CATransform3D myTransform = [(CALayer*)[myView.layer presentationLayer] transform];

[myView.layer removeAnimationForKey:@"Spin"];
[myView.layer setTransform:myTransform];
Run Code Online (Sandbox Code Playgroud)