拋物線動畫在Android中常用於模擬物體拋射效果,如商品飛入購物車、遊戲炮彈軌跡等。其核心原理基於物理運動方程:x = vx * t(水平位移),y = vy * t + 0.5 * g * t²(垂直位移),其中vx為水平初速度,vy為垂直初速度,g為重力加速度。

基礎實現

通過ValueAnimator動態計算座標:

val animator = ValueAnimator.ofFloat(0f, 1f).apply {     duration = 2000     addUpdateListener { animation ->         val progress = animation.animatedValue as Float         val currentX = startX + velocityX * progress         val currentY = startY + velocityY * progress + 0.5f * gravity * progress * progress         targetView.translationX = currentX         targetView.translationY = currentY     } } animator.start()

優化方案

貝塞爾曲線:使用PathInterpolator讓軌跡更自然,適合非物理精確場景。

性能優化:在列表中使用ViewPropertyAnimator減少計算開銷。

軌跡預覽:通過Path和PathEffect在開發階段調試路徑。

應用場景

電商應用:商品加入購物車的飛入效果。

遊戲開發:炮彈、投擲物的運動軌跡。

任務管理:任務完成時的動效反饋。

注意事項

避免在onDraw中頻繁計算,優先使用硬件加速。

複雜場景下,可結合MotionLayout實現更靈活的動畫編排。

通過合理選擇實現方式,拋物線動畫能顯著提升用户體驗,同時保持代碼簡潔高效。