上面已經介紹了TWEEN的動畫,下面就來介紹另一種動畫形式逐幀動畫的實現方式
定義AnimationDrawable對象,並向其中添加每幀的圖像,從而實現幀播放的動畫效果,實現方式如下
//定義animationDrawable對象
AnimationDrawable anima=new AnimationDrawable();
for(int i=1;i<=2;i++){
//獲取圖片id
int id = getResources().getIdentifier("pic"+i, "drawable", this.getContext().getPackageName());
//設置每幀動畫
Drawable mframe=getResources().getDrawable(id);
//第一個參數爲每幀的動畫,第二個參數爲該幀動畫的顯示時間
anima.addFrame(mframe, 500);
}
//true爲不重複播放,false反之
anima.setOneShot(false);
//設置顯示動畫到屏幕
this.setBackgroundDrawable(anima);
//開始播放動畫
anima.start();
逐幀動畫和Tween動畫一樣同樣可以通過xml來實現,實現方式如下,同樣是在res/anim下創建xml文件,item爲每幀動畫,drawable是每幀需要載入的畫面,duration和上面一樣是播放該幀畫面的時間,oneshot爲重複播放設定,也和函數時一致,false重複播放
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
<item android:drawable="@drawable/pic1" android:duration="500"></item>
<item android:drawable="@drawable/pic2" android:duration="500"></item>
</animation-list>
調用xml的代碼如下:
AnimationDrawable manima=null;
//通過imgview類來載入幀動畫,並將值賦給AnimationDrawable對象
ImageView img=new ImageView(this.getContext());
img.setBackgroundResource(R.anim.animation);
manima =(AnimationDrawable) img.getBackground();
this.setBackgroundDrawable(manima);
manima.start();
幀動畫的基本實現過程就介紹完了,需要注意的一點的就是緩存,緩存大小不夠的話,程序會直接down掉,所以需要根據實際情況添加緩存的大小