在用SurfaceView進行遊戲開發過程中,用到SurfaceHolder來處理它的Canvas上畫的效果和動畫是必不可少的。用於控製表面,大小,像素等。
Abstract interface to someone holding a display surface. Allows you to control the surface size and format,
edit the pixels in the surface, and monitor changes to the surface. This interface is typically available
through the SurfaceView class.
其中特別要注意以下的幾個函數:
abstract void addCallback(SurfaceHolder.Callback callback);
// 給SurfaceView當前的持有人一個回調對象。
abstract Canvas lockCanvas();
// 鎖定畫布,一般在鎖定後就可以通過其返回的畫布對象Canvas,在其上面畫圖等操作了。
abstract Canvas lockCanvas(Rect dirty);
// 鎖定畫布的某個地區進行畫圖等..因為畫完圖後,會調用下面的unlockCanvasAndPost來改變顯示內容。
// 相對部分記憶體要求比較高的遊戲來說,可以不用重畫dirty外的其它地區的像素,可以提高速度。
abstract void unlockCanvasAndPost(Canvas canvas);
// 結束鎖定畫圖,並提交改變。
例子:
class DrawThread extends Thread { private SurfaceHolder holder; private boolean running = true; protected DrawThread(SurfaceHolder holder) {this.holder = holder;} protected void doStop() { running = false; } public void run() { Canvas c = null; while( running ) { c = holder.lockCanvas(null); // 鎖定整個畫布,在記憶體要求比較高的情況下,建議參數不要為null try { synchronized(holder) { bGrid.drawGrid(c);//畫遊戲中的網格 BBoom.drawBooms(c, booms); //畫遊戲中的炸彈 bFairy.drawFairy(c);//畫遊戲中的主角 // 畫的內容是z軸的,後畫的會覆蓋前面畫的。 } } catch(Exception ex) {} finally { holder.unlockCanvasAndPost(c); //更新螢幕顯示內容 } } } };
轉自 http://blog.csdn.net/py890000/article/details/5439233