package com.example.test; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; import android.view.SurfaceView; /** * 继承SurfaceView * 实现SurfaceHolder.Callback。给SurfaceHolder用的 * 创建SurfaceHolder。并addCallback,SurfaceView的一切都有SurfaceHolder控制 */ public class MySurfaceView extends SurfaceView implements Callback, Runnable { //SurfaceView基本 private SurfaceHolder sfh;//操控SurfaceView private Paint p; private Canvas c; //线程 private Thread t; private boolean flag; //数据 private int screenW, screenH; private int xx = 100, yy = 100; public MySurfaceView(Context context) { super(context); sfh = this.getHolder(); sfh.addCallback(this); p = new Paint(); p.setColor(Color.RED); } @Override public boolean onTouchEvent(MotionEvent event) { xx = (int) event.getX(); yy = (int) event.getY(); return true; } public void myDraw() { try { //当SurfaceView不可编辑或尚未创建。会返回null c = sfh.lockCanvas(); if(c != null) { c.drawColor(Color.GREEN);//刷屏 c.drawText("me", xx, yy, p);//画 } } catch(Exception e) { } finally { if(c != null) { sfh.unlockCanvasAndPost(c); } } } //游戏逻辑 public void logic() { } @Override public void surfaceCreated(SurfaceHolder holder) { screenW = this.getWidth(); screenH = this.getHeight(); //线程的初始化和启动都写在create里面 flag = true; t = new Thread(this); t.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { flag = false; } @Override public void run() { while (flag) { //刷屏时间保持一致 //通常会在10~20帧左右 //每秒20帧:1000ms/20=50ms每帧 long start = System.currentTimeMillis(); myDraw(); logic(); long end = System.currentTimeMillis(); try { if(end - start < 50) { Thread.sleep(50 - (end-start)); } } catch (InterruptedException e) { e.printStackTrace(); } } } }
SurfaceView的生命周期: