Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

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

編輯:Android 開發實例

我個人比較愛逛貼吧,那裡總有大量搞笑的動態圖,看一會兒心情就會好很多,壓力也釋放掉不少。確實,比起一張靜態圖片,動態圖明顯更有意思。這類圖片通常是 GIF 格式,瀏覽器可以直接把它們播放成動畫。

可惜 Android 原生控件並不支援播放 GIF。我們都知道,要在 Android 裡顯示圖片,可以用 ImageView;但如果把一張 GIF 塞進 ImageView,它只會顯示第一幀,不會有任何動畫效果。

那難道 Android 裡就沒法播 GIF 了嗎?当然不是。既然 ImageView 的能力不夠,那就自己寫一個足夠強的控件。今天我們就來實現一個 PowerImageView,它既保留 ImageView 的全部原生功能,同時又能播放 GIF。

新建項目 PowerImageViewTest,這裡使用 Android 4.0 的 API。

由於是自定義控件,會用到自定義屬性,因此在 values 目錄下新建 attrs.xml。目前只需要一個 auto_play 屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="PowerImageView">
        <attr name="auto_play" format="boolean"></attr>
    </declare-styleable>

</resources>

接著編寫核心類 PowerImageView。因為要支援 ImageView 的所有功能,讓它繼承自 ImageView:

public class PowerImageView extends ImageView implements OnClickListener {

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

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

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

    /** GIF 圖片的寬度 */
    private int mImageWidth;

    /** GIF 圖片的高度 */
    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) {
            // 資源 id 不為 0 時,獲取該資源的流
            InputStream is = getResources().openRawResource(resourceId);
            // 使用 Movie 解碼
            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) {
            // GIF 圖片按自身尺寸測量
            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。
     *
     * @return 布局中指定資源的 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;
    }
}

代碼注釋已相當完整,這裡再提綱挈領地說一遍。我們重寫了 ImageView 的所有構造函數,因此 PowerImageView 的用法與 ImageView 完全一致。構造中最關鍵的一步是通過 getResourceId() 拿到圖片資源 id——這裡借助了 Java 反射讀取 TypedArray 內部的 mValue。拿到 id 後轉成 InputStream,交給 Movie.decodeStream() 解碼。若返回的 Movie 為 null,說明是普通圖片,什麼都不用做,父類已經處理好了;若不為 null,則說明是 GIF,接著讀取是否自動播放、圖片寬高等屬性。默認不允許自動播放,此時還要加載播放按鈕圖並註冊點擊事件。

隨後進入 onMeasure()。若判定為 GIF,就重設控件尺寸,讓它剛好容得下這張圖。

再到 onDraw()。這裡同樣先分流:普通圖片直接 super.onDraw() 交給 ImageView;GIF 圖片則先看是否允許自動播放——允許就直接調 playMovie() 並持續 invalidate 形成動畫;不允許則先畫第一幀、疊一個播放按鈕,等用戶點擊後再開始播。

playMovie() 的原理也不複雜:記錄動畫起始時間,取動畫總時長,用「當前時間減起始時間」對時長取模,得到此刻應顯示的幀對應的時間偏移,再用 Movie 把這一幀畫出來。每次調用推進一幀,連貫起來就成了動畫。返回值用來判斷是否播完:若已過時間大於等於動畫時長,說明一輪結束,返回 true。

PowerImageView 寫完,接下來看怎麼用。打開或新建 activity_main.xml:

<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 指定圖片即可,這裡的 anim 就是一張 GIF,並讓控件在布局中居中。

MainActivity 的代碼是自動生成的,不再貼出。AndroidManifest.xml 有一點要注意:部分 4.0 以上開啟硬件加速的機型會導致 GIF 播不出來,因此需要關閉硬件加速,通過 android:hardwareAccelerated 屬性完成:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.powerimageviewtest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:hardwareAccelerated="false" >
        <activity
            android:name="com.example.powerimageviewtest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

現在可以跑起來了:一打開只看到 GIF 的第一幀,點擊之後才開始播放。

再試試自動播放,只需在布局中加上自定義屬性:

<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>

這裡就用到了前面定義的 auto_play 屬性。設為 true 之後,播放按鈕不再出現,動畫會自動循環播放。

更妙的是,PowerImageView 完整繼承了 ImageView 的原生能力。只要指定的不是 GIF,它的表現就和 ImageView 沒有任何差別。換成一張普通 PNG 試試:

<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/conan" />

</RelativeLayout>

圖片正常顯示在正中間,正是普通 ImageView 的效果。你還可以照舊使用 android:scaleType 等屬性,用法與原生完全一致。這大概就是名副其實的「Power 版 ImageView」了。

源碼下載,請點擊這裡

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