在Android 中是不支援直接使用Gif 圖檔關聯播放幀動畫,如下動畫在Android 中是無法播放的:

650) this.width=650;"<
Android 提供了另外一種解決的辦法,就是使用AnimationDrawable 這一函數使其支援逐幀播放,但是如何把gif 圖檔打散開來,成為每一幀的圖檔呢?下面介紹兩種比較不錯的軟體,可以幫我們打散圖檔。
gifsplitter2.0
使用方法如下:
650) this.width=650;" height=253<
這一軟體分割圖檔都是bmp圖檔,圖檔比較大,這裡不推薦使用,盡量節省不必要的位元組,是以這裡推薦使用如下 軟體
easygifanimator
650) this.width=650;" height=606<
點選檔案将幀檔案導出即可
得到了幀檔案後我們可以就編寫代碼,在res目錄下建立anim動畫檔案夾,寫下如下代碼
<?xml version="1.0" encoding="UTF-8"?>
<animation-list android:oneshot="false"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:duration="150" android:drawable="@drawable/xiu0" />
<item android:duration="150" android:drawable="@drawable/xiu1" />
<item android:duration="150" android:drawable="@drawable/xiu2" />
<item android:duration="150" android:drawable="@drawable/xiu3" />
</animation-list>
對應的item 為順序的圖檔從開始到結束,duration為每張逐幀播放間隔,oneshot 為false 代表循環播放,設定為true 即播放一次即停止。
對應Activity 代碼如下編寫:
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class animActivity extends Activity implements OnClickListener {
ImageView iv = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView) findViewById(R.id.ImageView01);
iv.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
AnimationDrawable anim = null;
Object ob = iv.getBackground();
anim = (AnimationDrawable) ob;
anim.stop();
anim.start();
}
使用AnimationDrawable 對象獲得圖檔的圖檔,然後指定這個AnimationDrawable 開始播放動畫
Tip:使用此方法不會預設播放,必須要有事件觸發才可播放動畫,如上面的通過點選監聽觸發動畫的播放
那麼如何使用圖檔自動播放呢?我們可以聯想一下,ProgressBar 是不是預設的時候就會轉,那就是那個圓形的進度條,是的。我們可以對它進行改造合它也可以自動播放,在Values 檔案下建立一個styles 檔案,編寫如下代碼 :
<resources>
<style name="animStyle" parent="@android:style/Widget.ProgressBar.Large">
<item name="android:indeterminateDrawable">@anim/test</item>
</style>
</resources>
上面樣式檔案自Widget.ProgressBar.Large 為其設定動畫檔案,我們在XML中就可以通過設定它的樣式使其為我們工作
<ProgressBar android:id="@+id/ProgressBar01" style="@style/animStyle"
android:layout_width="128px" android:layout_height="128px"></ProgressBar>
OK,就是這麼簡單,下面看看運作效果: