【发布时间】:2010-04-01 10:52:55
【问题描述】:
我正在将 CABasicAnimation 应用于图层的位置属性,它的动画效果很好,但是在动画完成后它回到原始位置如何避免这种情况并使图像仅停留在动画位置?
【问题讨论】:
标签: iphone ios opengl-es core-animation
我正在将 CABasicAnimation 应用于图层的位置属性,它的动画效果很好,但是在动画完成后它回到原始位置如何避免这种情况并使图像仅停留在动画位置?
【问题讨论】:
标签: iphone ios opengl-es core-animation
有几种不同的方法可以解决这个问题。我最喜欢的是在动画结束时设置对象,并使用 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;
}
【讨论】:
您需要设置最终位置。如果你只使用 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
【讨论】:
animation.removedOnCompletion = NO;
要在动画结束时设置对象,只需像这样编写代码
#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 = .forwards;
animation.isRemovedOnCompletion = false
目标-C
animation.fillMode = kCAFillModeForwards; //The receiver remains visible in its final state when the animation is completed.
animation.removedOnCompletion = NO;
【讨论】:
如果您查看 addAnimation:forKey: 的文档,它会说“通常这是隐式调用的”。换句话说,你不应该直接调用它。您实际上应该执行以下操作,这比设置 from 和 to 值更容易,您只需直接在图层上设置值:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.duration = .3;
myLayer.actions = @{@"opacity": animation};
myLayer.opacity = 0;
这会将图层淡化到零不透明度。