SufaceView

用于画面刷新频繁的界面。可以在主线程之外的线程中向屏幕上绘图。
1、继承SurfaceView,实现Calback接口
public class GameView extends SurfaceView implements Callback
2、生成:surfaceHolder(现存管理器)对象,并将CallBack传递给surfaceHolder
SurfaceHolder surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
3、重写CallBack的三个方法
//在surface的大小发生改变时激发
public void surfaceChanged(SurfaceHolder holder,int format,int width,int height){}
//在创建时激发,一般在这里调用画图的线程。
public void surfaceCreated(SurfaceHolder holder){}
//销毁时激发,一般在这里将画图的线程停止、释放。
public void surfaceDestroyed(SurfaceHolder holder) {}

4、实现画图线程:

Canvas canvas = holder.lockCanvas(null);//获取画布(画笔)
线程里的操作要有同步块{
canvas.画
}
holder.unlockCanvasAndPost(c));//解锁画布(画笔),提交画好的图像

package fy.game.tank; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class Main extends Activity { public static int WIDTH,HEIGHT; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { WIDTH = getWindowManager().getDefaultDisplay().getWidth(); HEIGHT = getWindowManager().getDefaultDisplay().getHeight(); super.onCreate(savedInstanceState); setContentView(new GameView(this)); } }

 package fy.game.tank; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.SurfaceHolder.Callback; public class GameView extends SurfaceView implements Callback { GameThread thread ; public GameView(Context context) { super(context); SurfaceHolder holder = getHolder(); holder.addCallback(this); thread = new GameThread(holder); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub thread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub thread.run = false; } class GameThread extends Thread{ SurfaceHolder surfaceHolder; boolean run = true; public GameThread(SurfaceHolder surfaceHolder){ this.surfaceHolder = surfaceHolder; } public void run(){ int i = 0; Canvas c = null; Paint paint = new Paint(); paint.setColor(Color.RED); while(run){ try{ c = surfaceHolder.lockCanvas(); synchronized (surfaceHolder) { c.drawText(i+"", 20, 20, paint); i++; Thread.sleep(1000); } } catch (Exception e) { e.printStackTrace(); } finally{ if(c != null){ surfaceHolder.unlockCanvasAndPost(c); } } } } } }

你可能感兴趣的:(thread,c,exception,null,Class,callback)