/**
*/
public class MySurfaceView extends SurfaceView implements Callback, Runnable {
/** Called when the activity is first created. */
private SurfaceHolder sfh;
private Thread th;
private Canvas
canvas;
private Paint paint;
private int ScreenW, ScreenH;
public MySurfaceView(Context context) {
super(context);
th = new Thread(this);
sfh = this.getHolder();//通过SurfaceView的getHolder()函数可以获取SurfaceHolder对象,Surface 就在SurfaceHolder对象内。SurfaceView不会直接地处理Surface对象,必须通过SurfaceHolder来处理。因此当创建一个SurfaceView时,必须调用getHolder来取得SurfaceHolder。由辅助线程来描绘Surface。
sfh.addCallback(this); // 添加一个回调函数;执行完成后,马上就会回调 surfaceCreated方法了 然后开启线程 执行绘图方法这里这个执行顺序要搞清楚
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
paint.setTextSize(16);
this.setKeepScreenOn(true);// 保持屏幕常亮
}
@Override
public void startAnimation(Animation animation) {
super.startAnimation(animation);
}
/**
*/
public void surfaceCreated(SurfaceHolder holder) {
ScreenW = this.getWidth();// 备注2
ScreenH = this.getHeight();
th.start();
}
//绘图方法 注意这里是另起一个线程来执行绘图方法了不是在UI 线程了
private void draw() {
try {
//在 unlockCanvas() 和 lockCanvas()中Surface的内容是不缓存的,所以需要完全重绘Surface的内容,为了提高效率只重绘变化的部分则可以调用lockCanvas(Rect dirty)函数来指定一个dirty区域,这样该区域外的内容会缓存起来。
canvas = sfh.lockCanvas(); // 得到一个canvas实例,由SurfaceHolder的Canvas lockCanvas()或则Canvas lockCanvas(Rect dirty)函数来获取Canvas对象,但是在上面的画图是不会缓存的
canvas.drawColor(Color.WHITE);// 刷屏;
paint.setColor(Color.BLUE);
Bitmap bitmap = ((BitmapDrawable)(getResources().getDrawable(R.drawable.icon))).getBitmap();
Rect r = new Rect(20, 20, 20, 100);
canvas.drawBitmap(bitmap, DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_AUTO, paint);
} catch (Exception ex) {
} finally { // 备注3
if (canvas != null)
//当在Canvas中绘制完成后,调用函数unlockCanvasAndPost(Canvas canvas)来通知系统Surface已经绘制完成,这样系统会把绘制完的内容显示出来。
sfh.unlockCanvasAndPost(canvas);
}
}
public void run() {
while (true) {
draw();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}