Android備忘錄《幀動畫》

Ansong發表於2018-06-20

幀動畫

特點

  • 通過播放一組定義好的圖片,像電影哪種方式,來實現的一種動畫。
  • 三種動畫中實現最簡單的,由於是純載入圖片實現動畫,所以會消耗更多記憶體,也更容易產生OOM,所以使用圖片越小越好。
  • 通常用在一些簡單的Loading圖示,下拉上拉圖示等。
  • 作用於View(Button,TextView...),但不能修改View的屬性(背景,顏色,大小...)

實現方式

  • 通過XML檔案來定義

res/anim的資料夾裡建立動畫效果.xml檔案

xml程式碼

<?xml version="1.0" encoding="utf-8"?>
<animation-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true"> // 設定是否只播放一次,預設為false
    // item = 動畫圖片資源;duration = 設定一幀持續時間(ms)
    <item android:drawable="@drawable/a0" android:duration="100"/>
    <item android:drawable="@drawable/a1" android:duration="100"/>
    <item android:drawable="@drawable/a2" android:duration="100"/>
    <item android:drawable="@drawable/a3" android:duration="100"/>
    <item android:drawable="@drawable/a4" android:duration="100"/>
    <item android:drawable="@drawable/a5" android:duration="100"/>
</animation-list>
複製程式碼

啟動/停止

ImageView frameAnimationImage = (ImageView)findViewById(R.id.animation_frame_image);
frameAnimationImage.setImageResource(R.drawable.frame_animation_drawable);
AnimationDrawable animationDrawable = (AnimationDrawable) frameAnimationImage.getDrawable();
animationDrawable.start();

AnimationDrawable animationDrawable = (AnimationDrawable) frameAnimationImage.getDrawable();
animationDrawable.stop();
複製程式碼
  • 通過Java程式碼來實現
//Java程式碼實現幀動畫
AnimationDrawable animation = new AnimationDrawable();
//第一個引數為動畫圖片資源,第二個引數為執行時間
animation.addFrame(ContextCompat.getDrawable(context,R.drawable.frame_animation_a), 200);
animation.addFrame(ContextCompat.getDrawable(context,R.drawable.frame_animation_b), 200);
animation.addFrame(ContextCompat.getDrawable(context,R.drawable.frame_animation_c), 200);
animation.setOneShot(false);

frameAnimationImage.setImageDrawable(animation);
animation.stop();
//特別注意:在動畫start()之前要先stop(),不然在第一次動畫之後會停在最後一幀,這樣動畫就只會觸發一次
animation.start();
複製程式碼

相關文章