Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 逐幀動畫實作:AnimationDrawable 用法完整示範

編輯:關於 Android 程式設計

Android 的 AnimationDrawable 是最直覺的逐幀動畫方案,用起來就像翻頁動畫一樣,一張張圖片依序播放。整個流程可以拆成「定義動畫清單」與「在程式碼中啟動」兩部分。

第一步:在 drawable 下定義動畫清單

先在 drawable 資料夾建立一個 XML 檔,用 animation-list 作為根標籤,把每一幀寫成一個 item:

<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
    android:oneshot="true">
    <item android:drawable="@drawable/compass_1" android:duration="70" />
    <item android:drawable="@drawable/compass_2" android:duration="70" />
    <item android:drawable="@drawable/compass_3" android:duration="70" />
    <item android:drawable="@drawable/compass_4" android:duration="70" />
    <item android:drawable="@drawable/compass_5" android:duration="70" />
</animation-list>

幾個關鍵屬性說明:

  • android:oneshot:是否只播放一遍。設為 true 就播完停止,設成 false 則會無限循環。
  • android:duration:每一幀停留的時間,單位是毫秒。這裡每幀 70ms,五幀大約 0.35 秒跑完一輪。
  • android:drawable:該幀要顯示的圖片資源。

第二步:取出 AnimationDrawable 物件

定義好 XML 之後,在程式碼中把它轉成 AnimationDrawable:

AnimationDrawable ad = (AnimationDrawable) getResources().getDrawable(R.drawable.bootanimation);

第三步:設為背景並播放

接著把這個物件設成目前 View 的背景:

mView.setBackgroundDrawable(ad);

然後就能呼叫 ad.start() 與 ad.stop() 來啟動與停止動畫。

要特別注意:這個 Drawable 必須先被設為該 View 的背景,否則 start() 和 stop() 完全不會有任何效果。這是最容易踩到的一個坑。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved