转载出处http://www.cnblogs.com/xuling/archive/2011/06/06/android.html
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder surfaceHolder;//surface的控制器,用来操纵surface。处理它的Canvas上画的效果和动画,控制表面,大小,像素等。
MyTHread myTHread;
public MySurfaceView(Context context) {
super(context);
surfaceHolder = this.getHolder();
surfaceHolder.addCallback(this);
myTHread = new MyTHread(surfaceHolder);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
myTHread.isRun = true;
myTHread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
myTHread.isRun = false;
}
//画图线程
class MyTHread extends Thread
{
private SurfaceHolder holder;
public boolean isRun;
public MyTHread(SurfaceHolder holder) {
this.holder = holder;
isRun = true;
}
@Override
public void run() {
int count = 1;
while (isRun) {
Canvas c = null;
try {
synchronized (holder) {
//锁定画布,一般在锁定后就可以通过其返回的画布对象Canvas,在其上面画图等操作了。
c = holder.lockCanvas();
//(作画)
//设置画布背景颜色
c.drawColor(Color.BLACK);
Paint p = new Paint();
p.setColor(Color.WHITE);
Rect r = new Rect(100,50,300,250);
c.drawRect(r, p);
c.drawText("这是"+ (count++) +"秒", 100,310,p);
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null) {
holder.unlockCanvasAndPost(c);//结束锁定画图,并提交改变。
}
}
}
}
}
}