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

Android 進階系列(三):SurfaceView 搭配多執行緒,讓動畫不再卡頓

編輯:關於 Android 開發

上一節我們大致介紹了 SurfaceView 的基本用法,這一篇要談的是它與多執行緒的組合技。之所以要讓兩者搭配,主要是為了避免動畫閃爍——這其實是一種相當典型的 Android 繪圖優化手法。

先說明一下:Android 的多執行緒寫法與 Java 完全一樣,這裡就不再重複介紹 Thread 的基礎語法。本文直接切入主題:開一條執行緒專門讀取圖片,再開另一條執行緒專門負責繪圖。

實驗對照:一條執行緒 vs. 兩條執行緒

本文程式的執行結果如下。左邊是「單一執行緒邊讀邊畫」,右邊是「兩個執行緒分工,一個讀、一個畫」:

直接比對可以發現,右邊的動畫幀率明顯快過左邊,而且兩邊都沒有使用 Thread.sleep() 來控制節奏。

為什麼一定要拆成讀、畫兩條線?

關鍵在於 SurfaceView 的繪圖機制:每次繪圖時,它都會鎖定 Canvas。也就是說,同一片區域在這一次沒有畫完之前,下一次就無法再畫上去,繪圖與繪圖之間會互相排隊等待。

如果像左邊那樣在一條執行緒裡「讀一張、畫一張」,那麼解碼圖片的時間就會硬生生卡在繪圖流程中間,畫面自然容易延遲。因此想提升動畫播放效率,正確思路是:一條執行緒專心畫圖,另一條執行緒負責把下一張圖先做預處理(解碼)準備好,讓繪圖線 never 等米下鍋。

main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout android:id="@+id/LinearLayout01"
                android:layout_width="wrap_content" android:layout_height="wrap_content">
        <Button android:id="@+id/Button01" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="單個獨立線程">
        <Button android:id="@+id/Button02" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="兩個獨立線程">

    <SurfaceView android:id="@+id/SurfaceView01"
                android:layout_width="fill_parent" android:layout_height="fill_parent">

程式碼解析

整支程式由四個部分組成:一個 SurfaceHolder.Callback 回呼(用反射機制掃出 drawable 目錄裡所有圖片資源與尺寸)、一個「讀取並繪圖」的執行緒 Load_DrawImage、一個「只負責繪圖」的執行緒 DrawImage,以及一個「只負責讀取」的執行緒 LoadImage。

package com.testSurfaceView;

import java.lang.reflect.Field;
import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

public class testSurfaceView extends Activity {
    Button btnSingleThread, btnDoubleThread;
    SurfaceView sfv;
    SurfaceHolder sfh;
    ArrayList imgList = new ArrayList();
    int imgWidth, imgHeight;
    Bitmap bitmap;   // 獨立線程讀取,獨立線程繪圖

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnSingleThread = (Button) this.findViewById(R.id.Button01);
        btnDoubleThread = (Button) this.findViewById(R.id.Button02);
        btnSingleThread.setOnClickListener(new ClickEvent());
        btnDoubleThread.setOnClickListener(new ClickEvent());
        sfv = (SurfaceView) this.findViewById(R.id.SurfaceView01);
        sfh = sfv.getHolder();
        sfh.addCallback(new MyCallBack());   // 自動運行 surfaceCreated 以及 surfaceChanged
    }

    class ClickEvent implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (v == btnSingleThread) {
                new Load_DrawImage(0, 0).start();   // 開一條線程讀取並繪圖
            } else if (v == btnDoubleThread) {
                new LoadImage().start();                      // 開一條線程讀取
                new DrawImage(imgWidth + 10, 0).start();      // 開一條線程繪圖
            }
        }
    }

    class MyCallBack implements SurfaceHolder.Callback {
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            Log.i("Surface:", "Change");
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            Log.i("Surface:", "Create");

            // 用反射機制來獲取資源中的圖片 ID 和尺寸
            Field[] fields = R.drawable.class.getDeclaredFields();
            for (Field field : fields) {
                if (!"icon".equals(field.getName())) {   // 除了 icon 之外的圖片
                    int index = 0;
                    try {
                        index = field.getInt(R.drawable.class);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    imgList.add(index);   // 保存圖片 ID
                }
            }

            // 取得圖像大小
            Bitmap bmImg = BitmapFactory.decodeResource(getResources(), imgList.get(0));
            imgWidth = bmImg.getWidth();
            imgHeight = bmImg.getHeight();
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            Log.i("Surface:", "Destroy");
        }
    }

    /*
     * 讀取並顯示圖片的線程
     */
    class Load_DrawImage extends Thread {
        int x, y;
        int imgIndex = 0;

        public Load_DrawImage(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public void run() {
            while (true) {
                Canvas c = sfh.lockCanvas(new Rect(this.x, this.y, this.x + imgWidth, this.y + imgHeight));
                Bitmap bmImg = BitmapFactory.decodeResource(getResources(), imgList.get(imgIndex));
                c.drawBitmap(bmImg, this.x, this.y, new Paint());
                imgIndex++;
                if (imgIndex == imgList.size())
                    imgIndex = 0;

                sfh.unlockCanvasAndPost(c);   // 更新螢幕顯示內容
            }
        }
    };

    /*
     * 只負責繪圖的線程
     */
    class DrawImage extends Thread {
        int x, y;

        public DrawImage(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public void run() {
            while (true) {
                if (bitmap != null) {   // 如果圖像有效
                    Canvas c = sfh.lockCanvas(new Rect(this.x, this.y, this.x + imgWidth, this.y + imgHeight));
                    c.drawBitmap(bitmap, this.x, this.y, new Paint());
                    sfh.unlockCanvasAndPost(c);   // 更新螢幕顯示內容
                }
            }
        }
    };

    /*
     * 只負責讀取圖片的線程
     */
    class LoadImage extends Thread {
        int imgIndex = 0;

        public void run() {
            while (true) {
                bitmap = BitmapFactory.decodeResource(getResources(), imgList.get(imgIndex));
                imgIndex++;
                if (imgIndex == imgList.size())   // 如果到盡頭則重新讀取
                    imgIndex = 0;
            }
        }
    };
}

值得留意的是,讀取線程與繪圖線程共用同一個成員變數 bitmap:讀取端持續把解碼結果寫進去,繪圖端則是「有圖就畫」。這種生产者—消费者式的簡易結構,正是拆開兩條線程後幀率明顯提升的原因。若再進一步加上同步或雙緩衝機制,還能避免讀到寫到一半的中間狀態。

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