在特定点停止CABasicAnimation
我正在使用用CABasicAnimation
创build的旋转animation。 它旋转UIView
超过2秒。 但是当UIView
被触摸时,我需要能够阻止它。 如果删除animation,则视图与animation开始之前的位置相同。
这是我的animation代码:
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"];
如何将UIView
的旋转权限停止在何处? 我知道如何pipe理触摸部分,但我无法弄清楚如何在animation的当前angular度停止视图。
解决scheme:我通过获取表示层的angular度,删除animation和设置视图的变换来解决问题。 代码如下:
[self.view.layer removeAllAnimations]; CALayer* presentLayer = self.view.layer.presentationLayer; float currentAngle = [(NSNumber *)[presentLayer valueForKeyPath:@"transform.rotation.z"] floatValue]; self.view.transform = CGAffineTransformMakeRotation(currentAngle);
好问题! 为此,了解Core Animation架构是很有帮助的。
如果您查看描述Core Animation Rendering Architecture的Core Animation Programming Guide中的图表,可以看到有三棵树。
你有模型树。 那就是你设定你想要发生的事情的价值的地方。 然后是演示树。 就运行时而言,这是非常重要的事情。 然后,最后是渲染树。 这就是用户所看到的。
在你的情况下,你想要查询表示树的值。
这很容易做到。 对于附加了animation的视图,请获取layer
然后查找该layer
的值。 例如:
CATransform3D myTransform = [(CALayer*)[self.view.layer presentationLayer] transform];
没有办法“暂停”animation中stream。 你所能做的只是查询值,删除它,然后从你离开的地方重新创build它。
这有点痛苦!
看看我的其他一些post,我会详细介绍一下,例如
当应用程序从后台恢复时,在animation停止的位置恢复
不要忘了,当你添加一个视图的图层的animation,你实际上并没有改变基础视图的属性。 那么会发生什么? 我们会在animation停止的地方得到奇怪的效果,并且您可以看到原始位置的视图。
这就是您需要使用CAAnimation
的地方。 看看我对这个post的回答,我在这里覆盖:
CABasicAnimation旋转返回到原来的位置
您需要将旋转设置为presentationLayer的旋转,然后从图层中移除animation。 您可以在我的博客文章中阅读关于Hittestinganimation图层的表示层 。
设置最终旋转的代码将如下所示:
self.view.layer.transform = [(CALayer*)[self.view.layer presentationLayer] transform]; [self.view.layer removeAnimationForKey:@"rotationAnimation"];