Android中的SurfaceView類就是雙緩衝機制。因此,在進行Android遊戲開發時應盡量使用SurfaceView而不要使用View,這樣的話效率較高,並且SurfaceView的功能也更加完善。為了更容易的瞭解雙緩衝技術,下面介紹用View實現雙緩衝的方法。
在此需要說明一下,雙緩衝的核心技術就是先通過setBitmap方法將要繪製的所有的圖形繪製到一個Bitmap上,然後再來調用drawBitmap方法繪製出這個Bitmap,顯示在螢幕上。其具體的實現代碼如下:
先貼出View類代碼:
package com.lbz.pack.test;import android.content.Context;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Paint;import android.graphics.Bitmap.Config;import android.graphics.drawable.BitmapDrawable;import android.view.KeyEvent;import android.view.MotionEvent;import android.view.View;public class GameView extends View implements Runnable{ /* 聲明Bitmap對象 */ Bitmap mBitQQ = null; Paint mPaint = null; /* 建立一個緩衝區 */ Bitmap mSCBitmap = null; /* 建立Canvas對象 */ Canvas mCanvas = null; public GameView(Context context) { super(context); /* 裝載資源 */ mBitQQ = ((BitmapDrawable) getResources().getDrawable(R.drawable.qq)).getBitmap(); /* 建立螢幕大小的緩衝區 */ mSCBitmap=Bitmap.createBitmap(320, 480, Config.ARGB_8888); /* 建立Canvas */ mCanvas = new Canvas(); /* 設定將內容繪製在mSCBitmap上 */ mCanvas.setBitmap(mSCBitmap); mPaint = new Paint(); /* 將mBitQQ繪製到mSCBitmap上 */ mCanvas.drawBitmap(mBitQQ, 0, 0, mPaint); /* 開啟線程 */ new Thread(this).start(); } public void onDraw(Canvas canvas) { super.onDraw(canvas); /* 將mSCBitmap顯示到螢幕上 */ canvas.drawBitmap(mSCBitmap, 0, 0, mPaint); } // 觸筆事件 public boolean onTouchEvent(MotionEvent event) { return true; } // 按鍵按下事件 public boolean onKeyDown(int keyCode, KeyEvent event) { return true; } // 按鍵彈起事件 public boolean onKeyUp(int keyCode, KeyEvent event) { return false; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } /** * 線程處理 */ public void run() { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } //使用postInvalidate可以直接線上程中更新介面 postInvalidate(); } }}