1. 程式人生 > >Frame動畫的兩種方法(寫死的Xml與SD卡圖片動態載入)

Frame動畫的兩種方法(寫死的Xml與SD卡圖片動態載入)

注意:

有時動畫會出現停留在第一幀不播放的情況。

是因為window還沒有載入好。

所以最好這樣:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
initViews();// 要執行的動畫方法
super.onWindowFocusChanged(hasFocus);
}
第一種: Xml 
①:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true">  


<item android:drawable="@drawable/splash01" android:duration="3000" />      
<item android:drawable="@drawable/splash02" android:duration="3000" /> 
<item android:drawable="@drawable/splash03" android:duration="3000" />      
</animation-list>

看看內容應該是很好理解的,<animation-list>為動畫的總標籤,這裡面放著幀動畫 <item>標籤,也就是說若干<item>標籤的幀 組合在一起就是幀動畫了。<animation-list > 標籤中android:oneshot="false" 這是一個非常重要的屬性,預設為false 表示 動畫迴圈播放, 如果這裡寫true 則表示動畫只播發一次。 <item>標籤中記錄著每一幀的資訊android:drawable="@drawable/a"表示這一幀用的圖片為"a",下面以此類推。  android:duration="100" 表示這一幀持續100毫秒,可以根據這個值來調節動畫播放的速度。

②:
拿到佈局檔案中的ImageView
 imageView.setBackgroundResource(R.drawable.animation);
 /**通過ImageView物件拿到背景顯示的AnimationDrawable
 animationDrawable = (AnimationDrawable) imageView.getBackground();
③:
animationDrawable.start(); 開始這個動畫
animationDrawable.stop(); 結束這個動畫
animationDrawable.setAlpha(100);設定動畫的透明度, 取值範圍(0 - 255)
animationDrawable.setOneShot(true); 設定單次播放
animationDrawable.setOneShot(false); 設定迴圈播放
animationDrawable.isRunning(); 判斷動畫是否正在播放
animationDrawable.getNumberOfFrames(); 得到動畫的幀數

第二種: 從SD卡載入圖片

①:
ImageView  view = (ImageView) findViewById(R.id.splash_anim);
AnimationDrawable d = new AnimationDrawable();
view.setImageDrawable(d);
AnimationDrawable animationDrawable = (AnimationDrawable)view.getDrawable();

②:
ArrayList<Bitmap> list = new ArrayList<Bitmap>();
Bitmap bitmap = getImageFromLocal("splash01.jpg");
Bitmap bitma = getImageFromLocal("splash02.png");
Bitmap bitm = getImageFromLocal("splash03.png");


Log.i("animationDrawable", "圖片在新增轉化為bitmap");
Log.i("animationDrawable", "animationDrawable是否為空:"+(animationDrawable==null));
animationDrawable.addFrame(new BitmapDrawable(bitmap), 1000);
animationDrawable.addFrame(new BitmapDrawable(bitma), 1000);
animationDrawable.addFrame(new BitmapDrawable(bitm), 2000);
③:
animationDrawable.start(); 
/**
* 從SD卡載入圖片
* 
* @param imagePath
* @return
*/
public Bitmap getImageFromLocal(String name) {
String imagePath = "/mnt/sdcard/" + name;
File file = new File(imagePath);
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
file.setLastModified(System.currentTimeMillis());
return bitmap;
}
return null;
}