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

Android 開發系列(十七):在 TextView 中顯示 Gif 動態表情

編輯:關於 Android 程式設計

谷歌官方並沒有提供 Gif 顯示控制項(雖然在 Google 眼中這大概只是隨便敲敲鍵盤的事)。網路上的解法大致分成兩個方向,但只有一條路真的可行。

方案一:用 Movie 類當影片播放(不推薦)

把 Gif 當成影片來播,用 Movie 搭配 Canvas.drawMovie()。實測之後發現這條路並不靠譜:播放的 Gif 不是花屏就是全黑,而且可操作性極差——根本沒辦法把它嵌進 TextView 裡。建議各位果斷放棄這個思路。

方案二:拆解成多幀,用執行緒輪播(採用)

把 Gif 分解成多張圖片,再由一個機制按設定的時間間隔循環載入這些幀。而「如何分解」又有兩種做法:

  • 人工預先切幀:用工具把 Gif 拆成多張 png 放進資源檔,再按序載入。看起來笨,但效果最流暢、記憶體行為最可控。早期版本的手機 QQ 可能就是這麼做的。
  • 執行期即時解碼:用工具類即時解析 Gif 位元組流。看起來比較「高端」,但記憶體消耗大,而且現今很難找到一個完美的 Gif 解碼工具類。code.google.com 上有一個 gifView.jar,其軟解碼實作算相對完整(但仍有缺陷)。

本專案採用第二種思路:用 GifOpenHelper 對 Gif 解碼,把產生的一組 Bitmap 存進 ArrayList<Bitmap>,再由 Handler 驅動輪播。先聲明這個工具類並非原創,也有一些缺陷。

一、GifOpenHelper 的關鍵 API

這個類的實作細節涉及 LZW 解壓縮與 GIF 格式的區塊解析,篇幅龐大。實際使用時只需要掌握五個方法:

read(InputStream is)   // 讀取 Gif 串流,注意只接受 GIF 格式
getImage()             // 取得第一幀
nextBitmap()           // 取得下一幀
getFrameCount()        // 取得分解後的總幀數
nextDelay()            // 取得幀與幀之間的時間間隔(毫秒)

這裡想多說一句:不建議把這個類研究得太透。我們的目的是借重現成的工具做出想要的控件,而不是自己實作 Gif 編碼器。當然,如果你的目標是開發一個製作 Gif 的應用,那就得好好研究演算法了。

類別內部用 GifFrame 內部類把「Bitmap + delay」綁在一起,並以 Vector<GifFrame> 保存所有幀;setFrameindex() 中做了循環處理,索引超出範圍時歸零,从而实现无限循環播放。

二、MyTextView:可顯示動態圖片的 TextView

接下來是本文的核心——在原生 TextView 基礎上擴充,讓它同時支援靜態圖片、動態圖片,以及兩者與文字的混合顯示。這個類的註解寫得比較完整:

package com.example.android_qqfix;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.example.utils.FaceData;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.widget.TextView;

public class MyTextView extends TextView {

    /**
     * SpanInfo 用於存放一個要顯示的圖片(動態或靜態)的資訊:
     * 分解後的每一幀 mapList、替代文字的起始與結束位置、
     * 幀的總數、當前顯示的幀序號、幀間隔
     */
    private class SpanInfo {
        ArrayList<Bitmap> mapList;
        int start, end, frameCount, currentFrameIndex, delay;

        public SpanInfo() {
            mapList = new ArrayList<Bitmap>();
            start = end = frameCount = currentFrameIndex = delay = 0;
        }
    }

    /** 處理一個 TextView 中出現多個圖片的情況 */
    private ArrayList<SpanInfo> spanInfoList = null;

    private Handler handler;    // 處理從子執行緒傳來的消息
    private String myText;      // 存放 TextView 應該顯示的文本

    /**
     * 這三個建構方法一個都不能少,否則會產生 CastException。
     * 每個建構式中都為 spanInfoList 建立實例,
     * 有點浪費但保證不會有空指標異常。
     */
    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        spanInfoList = new ArrayList<SpanInfo>();
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        spanInfoList = new ArrayList<SpanInfo>();
    }

    public MyTextView(Context context) {
        super(context);
        spanInfoList = new ArrayList<SpanInfo>();
    }

    /**
     * 解析要顯示的文本,找出需要替換成圖片的片段。
     * 若命中 Gif 圖庫則呼叫 parseGif,命中靜態圖庫則呼叫 parseBmp。
     */
    private void parseText(String inputStr) {
        myText = inputStr;
        Pattern mPattern = Pattern.compile("\\\\..");
        Matcher mMatcher = mPattern.matcher(inputStr);

        while (mMatcher.find()) {
            String faceName = mMatcher.group();
            Integer faceId;

            if ((faceId = FaceData.gifFaceInfo.get(faceName)) != null) {
                parseGif(faceId, mMatcher.start(), mMatcher.end());
            } else if ((faceId = FaceData.staticFaceInfo.get(faceName)) != null) {
                parseBmp(faceId, mMatcher.start(), mMatcher.end());
            }
        }
    }

    /** 解析靜態圖片:幀數設為 1,最後別忘了加進 spanInfoList */
    private void parseBmp(int resourceId, int start, int end) {
        Bitmap bitmap = BitmapFactory.decodeResource(
            getContext().getResources(), resourceId);

        SpanInfo spanInfo = new SpanInfo();
        spanInfo.currentFrameIndex = 0;
        spanInfo.frameCount = 1;
        spanInfo.start = start;
        spanInfo.end = end;
        spanInfo.delay = 100;
        spanInfo.mapList.add(bitmap);

        spanInfoList.add(spanInfo);
    }

    /** 解析 Gif:與靜態圖的差別在於幀數大於 1,需要逐幀讀出 */
    private void parseGif(int resourceId, int start, int end) {
        GifOpenHelper helper = new GifOpenHelper();
        helper.read(getContext().getResources().openRawResource(resourceId));

        SpanInfo spanInfo = new SpanInfo();
        spanInfo.currentFrameIndex = 0;
        spanInfo.frameCount = helper.getFrameCount();
        spanInfo.start = start;
        spanInfo.end = end;
        spanInfo.mapList.add(helper.getImage());

        for (int i = 1; i < helper.getFrameCount(); i++) {
            spanInfo.mapList.add(helper.nextBitmap());
        }

        spanInfo.delay = helper.nextDelay();   // 取得每一幀之間的延遲
        spanInfoList.add(spanInfo);
    }

    /**
     * MyTextView 對外的介面。以後設定內容用 setSpanText() 而不是 setText()。
     */
    public void setSpanText(Handler handler, String text) {
        this.handler = handler;      // 取得 UI 的 Handler
        parseText(text);             // 解析字串

        TextRunnable r = new TextRunnable();
        handler.post(r);             // 丟進 UI 執行緒的訊息佇列
    }

    public class TextRunnable implements Runnable {
        @Override
        public void run() {
            SpannableString sb = new SpannableString("" + myText);
            int gifCount = 0;
            SpanInfo info;

            for (int i = 0; i < spanInfoList.size(); i++) {
                info = spanInfoList.get(i);

                // 用 gifCount 區分 Gif 與 Bmp:Gif 則 gifCount > 0
                if (info.mapList.size() > 1) {
                    gifCount++;
                }

                Bitmap bitmap = info.mapList.get(info.currentFrameIndex);
                // 索引加一後取餘數,實現循環顯示
                info.currentFrameIndex = (info.currentFrameIndex + 1) % info.frameCount;

                if (gifCount != 0) {
                    bitmap = Bitmap.createScaledBitmap(bitmap, 60, 60, true);
                } else {
                    bitmap = Bitmap.createScaledBitmap(bitmap, 30, 30, true);
                }

                ImageSpan imageSpan = new ImageSpan(getContext(), bitmap);
                sb.setSpan(imageSpan, info.start, info.end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            MyTextView.this.setText(sb);

            /**
             * 這一步是為了節省記憶體:
             * 若文本中只有靜態圖片,執行緒就此終止不再重複執行;
             * 若有動圖,則持續排下一輪。
             */
            if (gifCount != 0) {
                handler.postDelayed(this, info.delay);
            }
        }
    }
}

三、FaceData:表情資料的集中管理

把表情名稱與資源 id 的對應關係抽到一個獨立類別,並用靜態區塊完成初始化,避免空指標:

package com.example.utils;

import java.util.HashMap;
import com.example.android_qqfix.R;

public class FaceData {

    public static HashMap<String, Integer> gifFaceInfo;
    public static HashMap<String, Integer> staticFaceInfo;

    public static String[] gifFaceName = { "\\ji", "\\gl" };
    public static Integer[] gifFaceId = { R.raw.ji, R.raw.gl };

    public static int[] faceId = {
        R.drawable.f_static_000, R.drawable.f_static_001, R.drawable.f_static_002,
        R.drawable.f_static_003, R.drawable.f_static_004, R.drawable.f_static_005,
        R.drawable.f_static_006, R.drawable.f_static_009, R.drawable.f_static_010,
        R.drawable.f_static_011, R.drawable.f_static_012, R.drawable.f_static_013,
        R.drawable.f_static_014, R.drawable.f_static_015, R.drawable.f_static_017,
        R.drawable.f_static_018
    };

    public static String[] faceName = {
        "\\呲牙", "\\淘氣", "\\流汗", "\\偷笑", "\\再見", "\\敲打",
        "\\擦汗", "\\流淚", "\\掉淚", "\\小聲", "\\炫酷", "\\發狂",
        "\\委屈", "\\便便", "\\菜刀", "\\微笑", "\\色色", "\\害羞"
    };

    // 靜態區塊的使用
    static {
        gifFaceInfo = new HashMap<String, Integer>();
        staticFaceInfo = new HashMap<String, Integer>();

        for (int i = 0; i < gifFaceName.length; i++) {
            gifFaceInfo.put(gifFaceName[i], gifFaceId[i]);
        }
        for (int i = 0; i < faceId.length; i++) {
            staticFaceInfo.put(faceName[i], faceId[i]);
        }
    }
}

需要的話還可以再加幾個靜態方法來動態增刪表情,此處不再贅述。

四、使用效果與對比

MyTextView、GifOpenHelper、FaceData 三者搭配,就構成了一個相對獨立的自訂 TextView,具備顯示圖片的能力,而且外部不需要再自己寫 SpannableString 的處理邏輯,因為都封裝在內部了。

對比一下。這是未封裝前,Activity 中顯示表情所需的全部程式碼:

private void setFaceText(TextView textView, String text) {
    SpannableString spanStr = parseString(text);
    textView.setText(spanStr);
}

private void setFace(SpannableStringBuilder spb, String faceName) {
    Integer faceId = faceMap.get(faceName);
    if (faceId != null) {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), faceId);
        bitmap = Bitmap.createScaledBitmap(bitmap, 30, 30, true);
        ImageSpan imageSpan = new ImageSpan(this, bitmap);
        SpannableString spanStr = new SpannableString(faceName);
        spanStr.setSpan(imageSpan, 0, faceName.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spb.append(spanStr);
    } else {
        spb.append(faceName);
    }
}

private SpannableString parseString(String inputStr) {
    SpannableStringBuilder spb = new SpannableStringBuilder();
    Pattern mPattern = Pattern.compile("\\\\..");
    Matcher mMatcher = mPattern.matcher(inputStr);
    String tempStr = inputStr;

    while (mMatcher.find()) {
        int start = mMatcher.start();
        int end = mMatcher.end();
        spb.append(tempStr.substring(0, start));
        setFace(spb, mMatcher.group());
        tempStr = tempStr.substring(end, tempStr.length());
        mMatcher.reset(tempStr);
    }
    spb.append(tempStr);
    return new SpannableString(spb);
}

// 呼叫時
setFaceText(holder.textView, chatList.get(position).get(from[1]).toString());

而採用 MyTextView 封裝之後,呼叫變成一行:

holder.textView.setSpanText(handler, chatList.get(position).get(from[1]).toString());

可見設計 MyTextView 雖然要花點功夫,但換來的是呼叫端的極大簡化,而且原生支援動態表情。

另外注意:使用 MyTextView 時,版面檔中要把 TextView 換成自訂的完整類名:

<com.example.android_qqfix.MyTextView
    android:id="@+id/chatlist_text_me"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@id/chatlist_image_me"
    android:layout_alignTop="@id/chatlist_image_me"
    android:textSize="8pt"
    android:background="@drawable/balloon_back_right"
    android:paddingTop="13dip"
    android:paddingBottom="18dip" />

五、兩個實作上的關鍵說明

1. 不要在 MyTextView 內開子執行緒。直覺做法是自己開一個 Thread,每隔一段時間 sleep 之後對 Host Activity 的 Handler 送 Message。但這樣做系統仍然視為執行緒不安全,會報錯。可行的辦法是建立一個 Runnable,交由 UI 的 Handler 以 post() 與 postDelayed() 定時呼叫。這說明在 UI 執行緒上用 Runnable 排隊,比自行開 Thread 送 Message 更安全。

2. 為什麼要封裝成自訂 View?因為 QQ 聊天頁面的 ListView 裡有許多多個 TextView,在 UI 執行緒中逐一取得每個 TextView 的引用再同步控制它們的圖片,幾乎不可能維護。把控制邏輯下放到每個 TextView 自己身上,程式碼更簡潔,複用性也更好,對外只暴露 setSpanText(Handler, String) 一個方法。

六、這套設計的效能陷阱

這個實作在功能上可行,但以今天的標準來看有幾個明確的效能問題,新專案應避免:

  • 每幀都建立新的 Bitmap。Bitmap.createScaledBitmap() 在每次 run() 中都被呼叫,會持續產生記憶體垃圾,容易觸發 GC 抖動甚至 OOM。正確做法是在 parseGif() 階段就一次性完成縮放並快取,後續只取用不再配置。
  • Handler 無限循環播放。View 不可見或已 detach 時仍然繼續排下一幀,是純粹的浪費。應在 onDetachedFromWindow() 中 removeCallbacks(),並在 onAttachedToWindow() 中恢復。
  • Activity 記憶體洩漏風險。內部類 TextRunnable 持有外部 MyTextView 的引用,而訊息佇列可能讓它存活超過 Activity 生命週期。
  • 正則表達式未預編譯。Pattern.compile() 每次呼叫都重新編譯,應提為靜態常數。

若要在新專案中實作表情顯示,建議改用 ImageSpan 搭配 Glide 或 AnimationDrawable,或直接引入成熟的表情庫,能省下大量踩坑時間。

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