android 通過幀動畫方式播放Gif動畫


注意:經過本人測試,這個方法很耗內存, 圖片一多就崩了.慎用

<1>用工具(photoshop或者FireWorks)將GIF動畫圖片分解成多個GIF靜態圖片,然后保存在res\drawable目錄下。

<2>在res\anim目錄下定義這些GIF靜態圖片(假設將GIF動態圖片分解成6個圖片,anim1.gif....anim6.gif)。在frame_animation.xml文件中定義這些GIF文件,如下:

<animation-list  xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
 <item android:drawable="@drawable/anim1" android:duration="50"/>
 <item android:drawable="@drawable/anim2" android:duration="50"/>
 <item android:drawable="@drawable/anim3" android:duration="50"/>
 <item android:drawable="@drawable/anim4" android:duration="50"/>
 <item android:drawable="@drawable/anim5" android:duration="50"/>
 <item android:drawable="@drawable/anim6" android:duration="50"/>

</animation-list>

android:oneshot = false表示無限播放,為true時,表示播放一次。

<3>編寫完動畫文件后,就需要裝載動畫文件,並創建AnimationDrawable對象。

 AnimationDrawable anim = (AnimationDrawable) getResources().getDrawable(R.anim.frame_animation);

創建完AnimationDrawable對象后,可以將該對象做為ImageView組件的背景

ImageView image = (ImageView) findViewById(R.id.image);

image.setBackgroundDrawable(anim);

除了上面的裝載方式外,還有別的裝載方式:

ImageView image = (ImageView) findViewById(R.id.image);

image.setBackgroundResource(R.anim.frame_animation);

Object backgroundObject = image.getBackground();

AnimationDrawable anim = (AnimationDrawable) backgroundObject;

 

AnimationDrawable類中與幀動畫相關的方法有:

start:開始播放幀動畫。

stop:停止播放幀動畫。

setOneShot:設置動畫只播放一次。為true是表示只播放一次。

addFrame:向AnimationDrawable對象中添加新的幀。

isOneShot:判斷是否只播放一次。

getNumberOfFrames:返回動畫的幀數。

getFrame:根據幀索引獲得指定幀的Drawable對象。幀從0開始。

getDuration:獲得指定幀的停留時間。

setAlpha:設置幀的透明度。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM