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

Android 進階第三篇(下):SurfaceView 雙緩衝與讀圖繪圖分離

編輯:Android 開發實例

上一篇介紹了 SurfaceView 的基本用法,這次談雙緩衝。雙緩衝的存在是為了消滅動畫閃爍:先把下一幀畫在備用畫面上,畫好之後再一次換頁,使用者眼裡就永遠只看到完整的畫面。在 SurfaceView 上實作雙緩衝其實很單純——開一條專屬的執行緒,在裡面不斷「鎖定 Canvas → 繪圖 → 解鎖並提交」即可。

一個直觀的對照實驗

本文的程式同時準備了兩種模式,可以現場比較:

  • 單線程模式:一條執行緒裡又讀圖又畫圖。
  • 雙線程模式:一條專職讀圖(解碼 Bitmap),另一條專職繪圖。

兩者都沒有使用 Thread.sleep(),但右邊(雙線程)的幀率明顯高於左邊。原因在於 SurfaceView 每次繪圖都要鎖定 Canvas,也就是同一片區域這次還沒畫完,下一次就畫不進去。如果讀圖與繪圖擠在同一條線程裡,解碼的時間就會直接變成畫面的空檔;把解碼丟到另一條線程去,繪圖線程永遠有現成的 Bitmap 可以貼,Canvas 的佔用時間被壓到最短,幀率自然上去。

這就是「生產者與消費者」的經典分工:一條線程專門生產影像,一條線程專門消費影像,中間靠一個共享變數交接。

main.xml

<?xml version="1.0" encoding="utf-8"?>
<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="兩個獨立線程" />
    </LinearLayout>

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

用反射一次撈出所有圖片資源

這支程式的素材是 res/drawable 底下的一整批圖片。與其把 R.drawable.xxx 一個一個寫死,用反射去列舉 R.drawable 的所有欄位會乾脆得多——這也是 Java 反射機制在 Android 上少見但很實用的一個場景:

Field[] fields = R.drawable.class.getDeclaredFields();
for (Field field : fields) {
    if (!"icon".equals(field.getName())) {      // 排除 app 圖示
        int index = field.getInt(R.drawable.class);
        imgList.add(index);
    }
}

程式碼本體

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<Integer> imgList = new ArrayList<Integer>();
    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 / Changed
    }

    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 surfaceCreated(SurfaceHolder holder) {
            Log.i("Surface:", "Create");

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

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

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

        @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;
                }
            }
        }
    }
}

lockCanvas 的兩種用法

這支程式示範了兩種鎖定方式。不帶參數的 lockCanvas() 鎖定整個 Surface,適合全畫面重繪;帶 Rect 參數的版本只鎖定指定 dirty 區域,因為 SurfaceView 是「這次沒畫完、下次就畫不進去」,把更新範圍縮小可以顯著降低每次提交的負擔。搭配 unlockCanvasAndPost(c) 完成提交,螢幕才會真正更新。

從教學範例到可上線的動畫引擎

這支程式把重點講清楚了,但直接拿去 production 還有幾處要補:

  • 線程不會停:while (true) 沒有退出條件,Activity 銷毀後線程仍在跑,動畫會在背景繼續吃 CPU。實作時應加一個 volatile boolean running 旗標,在 surfaceDestroyed() 或 onDestroy() 設為 false。
  • 沒有幀率控制:空轉的 while 迴圈會把 CPU 佔滿。加上 Thread.sleep() 或用 System.nanoTime() 計算剩餘時間,把迴圈穩定在目標 FPS(例如 16ms 一幀)。
  • 共享變數沒有同步:bitmap 由讀取線程寫、繪圖線程讀,嚴格來說需要 volatile 或 synchronized 保證可見性;更完整的做法是用雙緩衝佇列(兩個 Bitmap 交替)避免繪圖中途被換掉而出現撕裂。
  • 記得回收 Bitmap:decodeResource 每幀都配置一塊新的記憶體,長時間播放容易觸發 GC 抖動。實務上會把素材預先解碼進記憶體陣列,或直接改用 BitmapFactory.Options.inBitmap 複用緩衝區。

把這四點補完,這個小範例就會長成一個堪用的動畫引擎骨架——而它的核心,其實只是「一條線程負責準備,一條線程負責呈現」這麼一句話。

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