Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 動畫實作:播放 GIF 動圖

編輯:關於 Android 程式設計

Android 原生的 ImageView 無法直接播放 GIF 動畫,但系統提供了 Movie 這個類別可以派上用場。做法是自訂一個 View,把 GIF 解碼成 Movie 物件,再依播放時間不斷重繪畫面,就能讓動圖動起來。

以下是一個可播放 GIF 的自訂 View:

package com.ttw.gif;

import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

public class GifMove extends View {

    private Movie mMovie;
    private InputStream is = null;
    private long mMovieStart;

    public GifMove(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public GifMove(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public GifMove(Context context) {
        super(context);
    }

    public void setGifSource(int source) {
        BitmapFactory.Options option = new BitmapFactory.Options();
        option.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(), source, option);

        // 依 GIF 原始尺寸調整 View 大小
        LayoutParams lp = this.getLayoutParams();
        lp.width = option.outWidth;
        lp.height = option.outHeight;
        this.setLayoutParams(lp);

        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                is = null;
            }
        }
        is = getResources().openRawResource(source);
        mMovie = Movie.decodeStream(is);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        long now = android.os.SystemClock.uptimeMillis();

        if (mMovieStart == 0) {
            mMovieStart = now;
        }

        if (mMovie != null) {
            int dur = mMovie.duration();
            if (dur == 0) {
                dur = 500;
            }
            // 依目前經過的時間換算該顯示的影格
            int relTime = (int) ((now - mMovieStart) % dur);
            mMovie.setTime(relTime);
            mMovie.draw(canvas, getWidth() - mMovie.width(), getHeight()
                    - mMovie.height());
            invalidate(); // 持續重繪,形成動畫
        }
        super.onDraw(canvas);
    }
}

關鍵在於 onDraw 中的邏輯:以系統的 uptime 當作時間基準,透過取餘運算把時間映射到對應的影格,呼叫 setTime() 設定目前要顯示的畫面,最後再呼叫 invalidate() 觸發下一輪重繪,動畫便會持續播放。使用時只要在版面中放入這個 View,並呼叫 setGifSource() 指定 GIF 資源即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved