[英]CABasicAnimation not changing its position property after animation completes
我正在為圖層的位置屬性應用 CABasicAnimation 動畫效果很好但是在動畫完成后它回到原始位置如何避免這種情況並使圖像僅停留在動畫位置?
有幾種不同的方法可以解決這個問題。 我最喜歡的是在動畫結束時設置對象,並使用 fromValue 而不是 toValue 來創建動畫。 您還可以同時設置 fromValue 和 toValue 來創建此效果。 IE
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
要在動畫結束時設置對象,只需編寫這樣的代碼
#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;
這會將圖層淡化到零不透明度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.