我正在将CABasicAnimation应用于动画效果良好的图层的位置属性,但是在动画完成后它会回到原始位置,如何避免这种情况并使图像仅保持在动画位置?
答案 0 :(得分:15)
有几种不同的方法可以解决这个问题。我最喜欢的是在动画结束时设置对象,并使用fromValue而不是toValue来创建动画。您还可以设置fromValue和toValue来创建此效果。即
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;
}
答案 1 :(得分:8)
您需要设置最终位置。如果您只使用动画fromValue和toValue,它将快速回到原始起点。动画在“播放”时使用视图/图层的副本,然后动画将在完成时显示原始视图/图层。
如果你没有明确地设置它,它会显示为快照,即使视图/图层从未真正移动过。
startPoint和endPoint是CGPoints,myView是动画的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
答案 2 :(得分:3)
要在动画结束时设置对象,只需编写如下代码
#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"];
答案 3 :(得分:1)
如果要保留最终值,可以将removedOnCompletion设置为NO。并且不要忘记设置fillMode。
animation.fillMode = kCAFillModeForwards; //The receiver remains visible in its final state when the animation is completed.
animation.removedOnCompletion = NO;
答案 4 :(得分:0)
如果您查看addAnimation:forKey:的文档,则会显示“通常会隐式调用此方法”。换句话说,你不应该直接调用它。您实际上打算执行以下操作,这比设置from和to值更容易,只需直接在图层上设置值:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.duration = .3;
myLayer.actions = @{@"opacity": animation};
myLayer.opacity = 0;
这会将图层淡化为零不透明度。