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

自製 PowerImageView:讓 ImageView 也能播放 GIF 動畫

編輯:關於 Android 程式設計

論壇裡總是有大量搞笑的動態圖,比靜態圖有意思得多。問題是 Android 原生的 ImageView 並不支援 GIF——把 GIF 設進去,它只會顯示第一張,完全不動。

解法是自己寫一個 PowerImageView:既保留 ImageView 的所有原生功能,又能播放 GIF。原理靠的是 android.graphics.Movie 這個類別。

自訂屬性

先在 values/attrs.xml 宣告一個控制是否自動播放的屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="PowerImageView">
        <attr name="auto_play" format="boolean"></attr>
    </declare-styleable>
</resources>

PowerImageView 類別

public class PowerImageView extends ImageView implements OnClickListener {

    /** 播放 GIF 動畫的關鍵類 */
    private Movie mMovie;

    /** 開始播放按鈕圖片 */
    private Bitmap mStartButton;

    /** 記錄動畫開始的時間 */
    private long mMovieStart;

    /** GIF 圖片的寬與高 */
    private int mImageWidth;
    private int mImageHeight;

    /** 是否正在播放、是否允許自動播放 */
    private boolean isPlaying;
    private boolean isAutoPlay;

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

    public PowerImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PowerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PowerImageView);
        int resourceId = getResourceId(a, context, attrs);
        if (resourceId != 0) {
            InputStream is = getResources().openRawResource(resourceId);
            mMovie = Movie.decodeStream(is);
            if (mMovie != null) {
                // 不為 null 表示這是 GIF,接著讀取自動播放屬性
                isAutoPlay = a.getBoolean(R.styleable.PowerImageView_auto_play, false);
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                mImageWidth = bitmap.getWidth();
                mImageHeight = bitmap.getHeight();
                bitmap.recycle();
                if (!isAutoPlay) {
                    mStartButton = BitmapFactory.decodeResource(
                            getResources(), R.drawable.start_play);
                    setOnClickListener(this);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == getId()) {
            isPlaying = true;
            invalidate();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mMovie == null) {
            // 普通圖片,交給父類處理
            super.onDraw(canvas);
        } else {
            if (isAutoPlay) {
                playMovie(canvas);
                invalidate();
            } else if (isPlaying) {
                if (playMovie(canvas)) {
                    isPlaying = false;
                }
                invalidate();
            } else {
                // 尚未播放:畫第一幀並疊上播放按鈕
                mMovie.setTime(0);
                mMovie.draw(canvas, 0, 0);
                int offsetW = (mImageWidth - mStartButton.getWidth()) / 2;
                int offsetH = (mImageHeight - mStartButton.getHeight()) / 2;
                canvas.drawBitmap(mStartButton, offsetW, offsetH, null);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mMovie != null) {
            setMeasuredDimension(mImageWidth, mImageHeight);
        }
    }

    /**
     * 播放 GIF 動畫。播放完成回傳 true,未完成回傳 false。
     */
    private boolean playMovie(Canvas canvas) {
        long now = SystemClock.uptimeMillis();
        if (mMovieStart == 0) {
            mMovieStart = now;
        }
        int duration = mMovie.duration();
        if (duration == 0) {
            duration = 1000;
        }
        int relTime = (int) ((now - mMovieStart) % duration);
        mMovie.setTime(relTime);
        mMovie.draw(canvas, 0, 0);
        if ((now - mMovieStart) >= duration) {
            mMovieStart = 0;
            return true;
        }
        return false;
    }

    /**
     * 透過反射取得 src 指定圖片資源對應的 id。
     * 沒有指定任何圖片資源就回傳 0。
     */
    private int getResourceId(TypedArray a, Context context, AttributeSet attrs) {
        try {
            Field field = TypedArray.class.getDeclaredField("mValue");
            field.setAccessible(true);
            TypedValue typedValueObject = (TypedValue) field.get(a);
            return typedValueObject.resourceId;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (a != null) {
                a.recycle();
            }
        }
        return 0;
    }
}

程式邏輯拆解

構造函數:重寫了全部三個建構子,讓 PowerImageView 的用法與 ImageView 完全一致。先用反射取得圖片資源 ID,轉成 InputStream 餵給 Movie.decodeStream()。若回傳 null 代表是普通圖片,什麼都不用做,父類都處理好了;若非 null 就是 GIF,接著讀取自動播放屬性與圖片尺寸。不允許自動播放時,還要載入播放按鈕並註冊點擊。

onMeasure:如果是 GIF,重新定義控件尺寸,讓它剛好放得下圖片。

onDraw:普通圖片直接 super.onDraw();GIF 則依自動播放與播放狀態分三種情況處理——自動播放就一路 playMovie();手動播放中則持續播放直到結束;還沒開始就畫第一幀加播放鈕。

playMovie:先記錄動畫起始時間與總時長,用「目前時間 − 起始時間」對總時長取餘數,算出此刻該顯示第幾幀,再交給 Movie 繪製。每次 invalidate() 觸發一次重繪,連續下來就成了動畫。返回值用來判斷是否播完。

使用方式

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.example.powerimageviewtest.PowerImageView
        android:id="@+id/image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/anim" />
</RelativeLayout>

用法與 ImageView 幾乎一樣,用 android:src 指定圖片即可。預設會顯示第一幀並疊上播放鈕,點一下才開始播。

想改成自動循環播放,加上自訂屬性:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:attr="https://schemas.android.com/apk/res/com.example.powerimageviewtest"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.example.powerimageviewtest.PowerImageView
        android:id="@+id/image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/anim"
        attr:auto_play="true" />
</RelativeLayout>

設成 true 之後播放鈕不再出現,動畫會自動循環。

一個必須關掉的開關

有些 Android 4.0 以上的機型在啟用硬體加速後,Movie 會畫不出東西。解法是在 Manifest 中關閉:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:hardwareAccelerated="false" >
    ...
</application>

關掉硬體加速會影響整個 App 的繪製效能,這是使用 Movie 方案無法迴避的代價。

今天的更好選擇

這個教學的價值在於理解 Movie 與自訂 View 的繪製機制。但實務上,載入 GIF 請直接用 Glide 或 Coil:

Glide.with(context).asGif().load(R.drawable.anim).into(imageView);

一行就搞定,而且內建記憶體管理、隊列控制與生命週期綁定,不會像手寫 Movie 那樣在 Activity 銷毀後仍持續 invalidate() 造成記憶體洩漏。此外 getResourceId() 那段反射取得 TypedArray 內部 mValue 的寫法,在新版 Android 上會被 hidden API 政策攔阻,如今應改用 a.getResourceId(R.styleable.PowerImageView_src, 0) 這類公開 API。

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