Android中播放Gif圖片的方法。
主要原理是取出Gif中的每一幀圖片,分別設置到ImageView上邊展示出來
使用到Code.Google上邊的一個開源類庫GifDecoder,下載不了的可以從我後邊給出的Demo中搬運。
準備一個類繼承自ImageView重寫其構造方法同時傳入一個輸入流。
<span style="font-size:18px;">public class GifDecoderView extends ImageView</span>
<span style="font-size:18px;">public GifDecoderView(Context context, InputStream is) {
super(context);
playGif(is);
}</span>
playGif是播放Gif圖片的主要方法,稍後給出。
在我們新建的類中增加5個參數,一個Boolean型變量去表示我們用來播放gif圖片的線程是不是運行狀態,一個GifDecoder的實例,一個bitmap對象用來儲存這個動畫的每一幀圖像,一個handler去更新UI線程的信息,一個Runnable實例用來處理畫出我們剛剛定義的bitmap的事情。
<span style="font-size:18px;"><span style="white-space:pre"> </span>private boolean isAni;
private GifPlayer gp;
private Bitmap bm;
private Handler handler = new Handler();
private Runnable playFrame = new Runnable() {
@Override
public void run() {
if (null != bm && !bm.isRecycled()) {
GifDecoderView.this.setImageBitmap(bm);
}
}
};</span>
Runnable對象中包含的是更新界面圖片的方法。
playGif方法:
<span style="font-size:18px;">private void playGif(InputStream is) {
gp = new GifPlayer();
gp.read(is);
isAni = true;
new Thread() {
public void run() {
final int frameCount = gp.getFrameCount();
final int loopCount = gp.getLoopCount();
do {
for (int i = 0; i < frameCount; i++) {
bm = gp.getFrame(i);
int t = gp.getDelay(i);
handler.post(playFrame);
try {
Thread.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} while (true);
};
}.start();
}</span>
新建一個activity引用我們自定義好的GifdecoderView,傳入要顯示的Gif圖片
這裏我是再assets目錄中放入了一個Gif圖片
<span style="font-size:18px;"><span style="white-space:pre"> </span>InputStream is = null;
try {
is = getAssets().open("7.gif");
} catch (IOException e) {
e.printStackTrace();
}
GifDecoderView view = new GifDecoderView(this, is);
setContentView(view);</span>
至此Gif圖片就可以播放出來了。