CABasicAnimation在animation完成后不改变其位置属性

我正在将CABasicAnimation应用于一层animation效果良好的位置属性,但是在animation完成其回到原始位置之后如何避免这种情况,并使图像只停留在animation位置?

有几种不同的方法来解决这个问题。 我最喜欢的是在animation的末尾设置对象,并使用fromValue而不是toValue来创buildanimation。 你也可以设置fromValue和toValue来创build这个效果。 即

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"]; animation.duration = 1.0; animation.fromValue = [NSValue valueWithCGPoint:startPoint]; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; viewToAnimate.center = endPoint; [viewToAnimate.layer addAnimation:animation forKey:@"slide"]; 

另一种做法是将自己设置为委托并执行:

 -(void)animationDidStop:(id)sender finished:(BOOL)finished { viewToAnimate.center = endPoint; } 

你需要设置最终的位置。 如果您仅使用从值和值中的animation,则会跳回原始起点。 animation在“播放”时使用视图/图层的副本,然后animation在完成时显示原始视图/图层。

如果你没有明确地设置它,即使视图/图层没有真正移动,它也会反弹回来。

startPoint和endPoint是CGPoints,myView是animation的UIView。

  CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"]; animation.duration = .3; animation.fromValue = [NSValue valueWithCGPoint:startPoint]; animation.toValue = [NSValue valueWithCGPoint:endPoint]; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; [myView.layer addAnimation:animation forKey:@"position"]; myView.layer.position = endPoint; // Must set end position, otherwise it jumps back 

要在animation结束处设置对象,只需像这样编写代码即可

 #import <QuartzCore/QuartzCore.h> CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"]; animation.duration = 1.0; animation.fromValue = [NSValue valueWithCGPoint:startPoint]; animation.timingFunction = [CAMediaTimingFunction functionWithName:easing]; animation.fillMode = kCAFillModeForwards; // This line will stop the animation at the end position of animation animation.autoreverses = NO; viewToAnimate.center = endPoint; [viewToAnimate.layer addAnimation:animation forKey:@"slide"]; 

如果要保留最终值,可以将removedOnCompletion设置为NO。 不要忘记设置fillMode。

 animation.fillMode = kCAFillModeForwards; //The receiver remains visible in its final state when the animation is completed. animation.removedOnCompletion = NO; 

如果您查看addAnimation:forKey:的文档,则会显示“通常这是隐式调用的”。 换句话说,你不应该直接调用它。 你实际上是想做下面的事情,比设置和设置值更简单,只需直接在图层上设置值即可:

 CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"]; animation.duration = .3; myLayer.actions = @{@"opacity": animation}; myLayer.opacity = 0; 

这将使图层淡化为零不透明度。