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

Android 自定義 GifView 進階:讓 src 屬性直接支援 GIF 播放

編輯:關於 Android 程式設計

上一篇我們的做法是在代碼中透過構造函數把 GIF 的資源 ID 傳進 GifView,能用但有點死板。這篇要把它升級成「和 ImageView 一樣好用」的元件:直接在佈局檔裡寫 android:src,由 GifView 自己設法取出資源 ID,再解碼播放。這樣想在畫面上放哪張動圖,改 XML 就夠了,靈活度提升不少。

核心思路

GifView 繼承自 ImageView,好處是萬一 movie 解碼失敗(也就是使用者設的是普通靜態圖),可以直接把繪製工作交回父類的 onDraw(),等於天生向下相容。取得 src 資源 ID 這一步,Android 標準 API 沒有開放,實務上常見的作法是透過反射讀取 TypedArray 內部的 mValue 欄位,再取出其中的 resourceId。

GifView 完整代碼

package com.home.gifview;

import java.io.InputStream;
import java.lang.reflect.Field;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;

public class GifView extends ImageView {

    private Movie movie;
    private long movieStart;
    private int imageWidth;
    private int imageHeight;

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

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

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

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GifView);
        int resourceId = getResourceId(a, context, attrs);

        if (resourceId != 0) {
            InputStream is = getResources().openRawResource(resourceId);
            movie = Movie.decodeStream(is);
            if (movie != null) {
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                imageWidth = bitmap.getWidth();
                imageHeight = bitmap.getHeight();
                bitmap.recycle();
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (movie == null) {
            // 不是 GIF,交回父類照一般圖片繪製
            super.onDraw(canvas);
        } else {
            playGif(canvas);
            invalidate();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (movie != null) {
            // GIF 的情況直接以圖片本身的尺寸作為測量結果
            setMeasuredDimension(imageWidth, imageHeight);
        }
    }

    /**
     * 播放 GIF 動畫
     */
    private boolean playGif(Canvas canvas) {
        long now = SystemClock.uptimeMillis();
        if (movieStart == 0) {
            movieStart = now;
        }
        int duration = movie.duration();
        if (duration == 0) {
            duration = 1000;
        }
        int relTime = (int) ((now - movieStart) % duration);
        movie.setTime(relTime);
        movie.draw(canvas, 0, 0);
        if ((now - movieStart) >= duration) {
            movieStart = 0;
            return true;
        }
        return false;
    }

    /**
     * 以反射方式取得 src 指定圖片資源對應的 ID
     */
    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;
    }
}

自訂屬性宣告(attrs.xml)

因為我們沿用了 ImageView 既有的 src 屬性,declare-styleable 標籤本身可以是空的,主要是為了讓 obtainStyledAttributes() 有一個對應的宣告可查。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="GifView"></declare-styleable>
</resources>

佈局檔 main.xml

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

    <com.home.gifview.GifView
        android:id="@+id/main_gifView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/loading" />

</RelativeLayout>

別忘了關閉硬體加速

在 Android 4.0 以後的機型上,開啟硬體加速會讓 Movie 的繪製失效,動圖往往只剩一張靜態畫面。在 Activity 或 application 節點加上下面這行即可避開這個坑:

android:hardwareAccelerated="false"

小提醒:反射讀取 mValue 属于非公開 API,不同 Android 版本或更換實作後有失效風險。若要用在正式專案,建議包一層例外處理,或改用自建 declare-styleable 定義一個專屬屬性(例如 gifview:src),會更穩妥。

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