在特定点停止CABasicAnimation

Tho*_*sen 6 iphone core-animation objective-c ipad ios

我正在使用创建的旋转动画CABasicAnimation.它旋转UIView超过2秒.但我需要能够在UIView触摸时停止它.如果我删除动画,则视图与动画开始前的位置相同.

这是我的动画代码:

float duration = 2.0;
float rotationAngle = rotationDirection * ang * speed * duration;
//rotationAngle =  3*(2*M_PI);//(double)rotationAngle % (double)(2*M_PI) ;
CABasicAnimation* rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat: rotationAngle ];
rotationAnimation.duration = duration;
rotationAnimation.cumulative = YES;
rotationAnimation.removedOnCompletion = NO;
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
rotationAnimation.fillMode = kCAFillModeForwards;
rotationAnimation.delegate = self;

[self.view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
Run Code Online (Sandbox Code Playgroud)

如何在UIView旋转时将旋转停在哪里?我知道如何管理触摸部分,但我无法弄清楚如何在动画的当前角度停止视图.

解决方案: 我通过获取表示层的角度,移除动画并设置视图的变换来解决问题.这是代码:

[self.view.layer removeAllAnimations];      
CALayer* presentLayer = self.view.layer.presentationLayer; 
float currentAngle = [(NSNumber *)[presentLayer valueForKeyPath:@"transform.rotation.z"] floatValue];
self.view.transform = CGAffineTransformMakeRotation(currentAngle);
Run Code Online (Sandbox Code Playgroud)

Max*_*eod 16

好问题!为此,了解Core Animation架构很有帮助.

如果您查看核心动画编程指南中描述核心动画渲染架构的图表,您可以看到有三棵树.

你有模型树.这就是你设置你想要发生的事情的价值所在.然后是演示树.就运行时而言,这就是几乎所发生的事情.然后,最后是渲染树.这就是用户看到的内容.

在您的情况下,您要查询表示树的值.

这很容易做到.对于已附加动画的视图,获取layer并为此layer查询presentationLayer的值.例如:

CATransform3D myTransform = [(CALayer*)[self.view.layer presentationLayer] transform];
Run Code Online (Sandbox Code Playgroud)

没有办法"暂停"动画中流.您所能做的就是查询值,将其删除,然后从中断处重新创建它.

这有点痛苦!

看看我的其他一些帖子,我会更详细地介绍一下,例如

当应用程序从后台恢复时,恢复动画停止的位置

不要忘记,当您向视图的图层添加动画时,实际上并没有更改基础视图的属性.那会发生什么?我们会在动画停止的地方产生奇怪的效果,然后你会看到原始位置的视图.

这就是你需要使用CAAnimation代表的地方.看看我对这篇文章的回答,我将其覆盖:

CABasicAnimation旋转返回原始位置


Dav*_*ist 5

您需要将旋转设置为presentationLayer的旋转,然后从图层中删除动画.您可以在我的博客文章中阅读关于命中测试动画图层的表示层.

设置最终轮换的代码如下:

self.view.layer.transform = [(CALayer*)[self.view.layer presentationLayer] transform];
[self.view.layer removeAnimationForKey:@"rotationAnimation"];
Run Code Online (Sandbox Code Playgroud)