有没有办法暂停CABasicAnimation?

我有一个iPhone的基本旋转动画。 有什么办法可以“暂停”动画,以保持视图的位置? 我想这样做的一种方式是导致动画“完成”而不是调用“删除”它,我将如何做到这一点?

CABasicAnimation* rotationAnimation;
rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2];
rotationAnimation.duration = 100;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = HUGE_VALF;
rotationAnimation.removedOnCompletion = NO;
rotationAnimation.fillMode = kCAFillModeForwards;
[myView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

最近出现的Apple的技术说明QA1673描述了如何暂停/恢复图层的动画。

下面暂停和恢复动画列表:

-(void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

-(void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}

编辑: iOS 10引入了新的API - UIViewPropertyAnimator,它允许更交互地处理动画,例如它可以很容易地暂停和恢复动画,或者将它“查找”到某个特定的进度值。


Swift 3的答案:

Credits @Vladimir

码:

 func pauseAnimation(){
  var pausedTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
  layer.speed = 0.0
  layer.timeOffset = pausedTime
}

func resumeAnimation(){
  var pausedTime = layer.timeOffset
  layer.speed = 1.0
  layer.timeOffset = 0.0
  layer.beginTime = 0.0
  let timeSincePause = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime
  layer.beginTime = timeSincePause
}

设置视图图层的当前状态以匹配presentationLayer的状态,然后删除动画:

CALayer *pLayer = [myView.layer presentationLayer];
myView.layer.transform = pLayer.transform;
[myView.layer removeAnimationForKey:@"rotationAnimation"];
链接地址: http://www.djcxy.com/p/74203.html

上一篇: Is there a way to pause a CABasicAnimation?

下一篇: Animate a line using CALayer in NSView