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

Android 應用實戰:讓 ImageView 完美播放 GIF 動畫(附源碼)

編輯:關於 Android 程式設計

前言

大家都知道,ImageView 並不能很好地加載 GIF 圖片。如果你把 src 指向一個 gif 資源,畫面往往會永遠停在第一幀,看不到任何動畫效果。不過只要稍加改造,就能讓 GIF 在 ImageView 上完美播放起來。

思路

Android 為我們提供了一個 Movie 類(android.graphics.Movie),可以實現加載 gif 資源的目標。核心思路很簡單:自定義一個 ImageView 的子類,重寫其中的 onDraw 方法來逐幀繪制 gif。

(提示:閱讀本文需要具備自定義 View 的相關基礎知識。)

attrs 資源文件

先在 attrs 中定義一個自定義屬性 isgifimage,讓開發者能自行指定控件加載的是否為 gif 資源。之所以要加這個開關,是因為 Movie 加載普通圖片也能顯示,只是效率不如原生方式;默認值設為 true,即默認按 gif 處理。

<resources>
    <declare-styleable name="GifView">
        <attr name="isgifimage" format="boolean"/>
    </declare-styleable>
</resources>

構造函數

public GifView(Context context, AttributeSet attrs) {
    super(context, attrs);
    // 獲取自定義屬性 isgifimage
    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.GifView);
    isGifImage = array.getBoolean(R.styleable.GifView_isgifimage, true);
    array.recycle(); // 用完必須 recycle,否則影響下次獲取
    // 獲取 ImageView 原生的 src 屬性
    image = attrs.getAttributeResourceValue(
            "https://schemas.android.com/apk/res/android", "src", 0);
    movie = Movie.decodeStream(getResources().openRawResource(image));
}

構造方法裡主要做兩件事:獲取自定義屬性與加載 gif。這裡有兩個細節要強調:

  • R.styleable.GifView_isgifimage 是「styleable 名字 + 下劃線 + 屬性名字」拼成的,中間用下劃線分隔;
  • TypedArray 是公共資源,用完一定要調用 recycle(),否則會影響下次獲取自定義屬性。

隨後通過 attrs.getAttributeResourceValue 拿到 ImageView 原生的 src,再交給 Movie.decodeStream 解碼。

onDraw 方法

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas); // 先執行父類方法,繪制非 gif 資源
    if (isGifImage) {     // 若為 gif,執行 DrawGifImage(默認走這裡)
        DrawGifImage(canvas);
    }
}

private void DrawGifImage(Canvas canvas) {
    long nowTime = android.os.SystemClock.currentThreadTimeMillis();
    if (movieStart == 0) {
        movieStart = nowTime; // 第一次加載時記錄起始時間
    }
    if (movie != null) {      // 容錯處理
        int duration = movie.duration(); // gif 動畫總時長
        if (duration > 0) {
            // 根據系統時間推算當前應顯示的幀所在時間點
            int relTime = (int) ((nowTime - movieStart) % duration);
            movie.setTime(relTime);
            movie.draw(canvas, 0, 0); // 渲染 gif 當前幀
            invalidate();             // 刷新,播放下一幀
        }
    }
}

這裡的邏輯是:先判斷 isGifImage,若開發者設為 false 就直接走 super.onDraw 即可,避免不必要的 invalidate 開銷——畢竟不斷刷新對性能還是有一定消耗的。若需要繪制 gif,則依據系統時間推算當前時刻 gif 應顯示的時間幀,調用 setTime 定位、draw 渲染,再靠 invalidate 驅動下一幀,如此循環便實現了動畫。

布局中引用

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:gifview="https://schemas.android.com/apk/res/com.net168.testgifview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.net168.gifview.GifView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image"
        gifview:isgifimage="false" />
</LinearLayout>

引用時要注意 xmlns:gifview 的命名空間,其中最後一段必須是 GifView.java 所在的包名,這樣自定义屬性 gifview:isgifimage 才能被正確識別。通過這個小小的 GifView,你的應用就能輕鬆播放炫酷的 GIF 動畫了。

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