2024年3月12日发(作者:)

在用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(ck callback);

// 给SurfaceView当前的持有者一个回调对象。

abstract Canvas lockCanvas();

// 锁定画布,一般在锁定后就可以通过其返回的画布对象Canvas,在其上面画图等

操作了。

abstract Canvas lockCanvas(Rect dirty);

// 锁定画布的某个区域进行画图等..因为画完图后,会调用下面的

unlockCanvasAndPost来改变显示内容。

// 相对部分内存要求比较高的游戏来说,可以不用重画dirty外的其它区域的像素,

可以提高速度。

abstract void unlockCanvasAndPost(Canvas canvas);

// 结束锁定画图,并提交改变。

例子:

// 请参考上一篇文章:android中用SurfaceView做游戏开发

class DrawThread extends Thread {

private SurfaceHolder holder;

private boolean running = true;

protected DrawThread(SurfaceHolder holder) { = holder;}

protected void doStop() { running = false; }

public void run() {

Canvas c = null;

while( running ) {