幀動畫是Android開發中實現動態效果的基礎方式,通過快速切換靜態圖像序列產生視覺連續性。其核心原理基於人眼視覺暫留效應,適用於圖標狀態變化、簡單遊戲動畫等場景。
實現步驟與關鍵代碼
資源準備:在res/drawable目錄創建XML文件,定義動畫幀序列:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/frame1" android:duration="100"/> <item android:drawable="@drawable/frame2" android:duration="100"/> </animation-list>
代碼控制:
AnimationDrawable anim = (AnimationDrawable) getDrawable(R.drawable.my_animation); ImageView imageView = findViewById(R.id.image_view); imageView.setImageDrawable(anim); anim.start(); // 啓動動畫
性能優化要點
內存管理:單幀圖片尺寸建議不超過屏幕分辨率,複雜動畫推薦使用Lottie等矢量方案
生命週期適配:在onPause()中調用anim.stop()防止內存泄漏
幀率控制:通過duration屬性平衡流暢度與性能,一般30fps足
與屬性動畫對比
特性
幀動畫
屬性動畫
適用場景
簡單序列圖像
複雜屬性變化
資源消耗
高(需加載多張圖片)
低(純代碼實現)
靈活性
較低
高
幀動畫的優勢在於實現簡單直觀,但需注意避免過度使用導致應用卡頓。對於複雜動畫需求,建議結合ViewPropertyAnimator或MotionLayout實現。