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

自定義 GifView:在 Android 上播放 GIF 動畫

編輯:關於 Android 程式設計

GIF 在網頁開發裡隨處可見,很多動畫效果不必再寫程式碼就能呈現,App 中的使用也越來越多。但 Android SDK 並沒有現成的 GifView,因此只能自己打造一個 View。

好消息是 SDK 提供了 Movie 這個類別,它是實作 GifView 的關鍵:一個方法依播放時間決定目前該顯示哪一幀,另一個方法把該幀繪製到畫布上。兩者搭配就能完成播放。

點擊暫停按鈕後,動畫會停在當前幀。

步驟一:定義自訂屬性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="gifCommon">
        <attr name="gif_src" format="reference" />
        <attr name="decode_stream" format="boolean" />
        <attr name="default_animation_time" format="integer" />
    </declare-styleable>
</resources>

三個屬性分別對應:GIF 資源、是否以串流方式解碼、以及 GIF 本身未提供時長資訊時的預設循環間隔。

步驟二:實作 GifView

public class GifView extends View {

    private Movie mMovie;
    /** 動畫起始時間 */
    private long mMovieStart;
    private boolean mPaused = false;
    /** 目前幀對應的時間點 */
    private int mCurrentAnimationTime;

    private boolean decodeStream;
    private int srcId;
    private int defaultTime;

    public GifView(Context context) {
        this(context, null);
    }

    public GifView(Context context, AttributeSet set) {
        super(context, set);
        init(context, set);
    }

    private void init(Context context, AttributeSet set) {
        TypedArray a = context.obtainStyledAttributes(set, R.styleable.gifCommon);
        srcId = a.getResourceId(R.styleable.gifCommon_gif_src, -1);
        decodeStream = a.getBoolean(R.styleable.gifCommon_decode_stream, true);
        defaultTime = a.getInteger(R.styleable.gifCommon_default_animation_time, 1000);
        a.recycle();

        setFocusable(true);
        InputStream is = context.getResources().openRawResource(srcId);
        if (decodeStream) {
            mMovie = Movie.decodeStream(is);
        } else {
            mMovie = Movie.decodeByteArray(streamToBytes(is), 0,
                    streamToBytes(is).length);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mMovie == null) return;
        if (!mPaused) {
            updateAnimationTime();
            drawMovieFrame(canvas);
            invalidate();   // 持續驅動下一幀
        } else {
            drawMovieFrame(canvas);  // 暫停時只畫當前幀
        }
    }

    private void updateAnimationTime() {
        long now = android.os.SystemClock.uptimeMillis();
        if (mMovieStart == 0) {
            mMovieStart = now;
        }
        int dur = mMovie.duration();
        if (dur == 0) {
            dur = defaultTime;
        }
        mCurrentAnimationTime = (int) ((now - mMovieStart) % dur);
    }

    private void drawMovieFrame(Canvas canvas) {
        mMovie.setTime(mCurrentAnimationTime);
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        mMovie.draw(canvas, 0, 0);
        canvas.restore();
    }

    /** 控制暫停與續播 */
    public void setPaused(boolean paused) {
        this.mPaused = paused;
        if (!paused) {
            // 續播時重算起點,避免動畫跳格
            mMovieStart = android.os.SystemClock.uptimeMillis() - mCurrentAnimationTime;
        }
        invalidate();
    }

    public boolean isPaused() {
        return mPaused;
    }

    /** 讓自訂 View 支援 wrap_content */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width, height;
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else {
            int desired = (int) (getPaddingLeft() + mMovie.width() + getPaddingRight());
            width = Math.min(desired, widthSize);
        }
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else {
            int desired = (int) (getPaddingTop() + mMovie.height() + getPaddingBottom());
            height = Math.min(desired, heightSize);
        }
        setMeasuredDimension(width, height);
    }

    /** 串流轉位元組陣列 */
    private static byte[] streamToBytes(InputStream is) {
        ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = is.read(buffer)) >= 0) {
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
            Log.e("GifView", "讀取串流失敗", e);
        }
        return os.toByteArray();
    }
}

步驟三:在布局中使用

用法與一般 View 無異,記得加上自訂命名空間:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:gif="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fed952"
    android:gravity="center">

    <view.GifView
        android:id="@+id/gif_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        gif:decode_stream="true"
        gif:default_animation_time="1000"
        gif:gif_src="@drawable/animated_gif" />

    <TextView
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/gif_view"
        android:text="暫停" />
</RelativeLayout>

關鍵設計說明

  • onDraw 中自我驅動:每次繪製完畢呼叫 invalidate(),形成類似動畫迴圈的效果。
  • 取模運算定位幀:(now - start) % duration 讓動畫自動無限循環。
  • 暫停的處理:暫停時停止推進時間,續播時以「現在時間減去目前幀時間」重設起點,畫面才不會跳動。
  • 兩種解碼模式:串流解碼省記憶體,位元組陣列解碼則可重複使用同一份資料。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved