今天来说说SurfaceView吧
这东西的特性大家记住一个就行了,它的绘制是在子线程中,所以不堵塞UI,非常适合一些复杂的绘制
SuufaceView有一个重要的对象,是SurfaceHolder,通过getHolder()来获取,这个对象主要用于控制SurfaceView的声明周期,
以及获得和释放Canvas,废话不多说,来上一个流程图吧
public class SurfaceView_example extends SurfaceView implements Callback, Runnable { private SurfaceHolder mHolder; /** * 与SurfaceHolder绑定的Canvas */ private Canvas mCanvas; /** * 用于绘制的线程 */ private Thread t; /** * 线程的控制开关 */ private boolean isRunning; public SurfaceView_example(Context context) { super(context,null); // TODO Auto-generated constructor stub } public SurfaceView_example(Context context, AttributeSet attrs) { super(context, attrs); mHolder = getHolder(); mHolder.addCallback(this); //设置可获取焦点 setFocusable(true); setFocusableInTouchMode(true); //设置常亮 this.setKeepScreenOn(true); } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { isRunning = true; t = new Thread(this); t.start(); } @Override public void surfaceDestroyed(SurfaceHolder arg0) { isRunning = false; } @Override public void run() { while(isRunning){ darw(); } } private void darw() { try { mCanvas = mHolder.lockCanvas(); if(mCanvas != null){ //drawing } } catch (Exception e) { } finally{ if(mCanvas != null){ mHolder.unlockCanvasAndPost(mCanvas); } } } }
简单地说,就是在surfaceCreated里面起一个线程,然后线程里面用holder锁定Canvas对象,有了canvas就可以绘制了,通常是间隔一段时间(例如100ms)绘制,生命周期结束的时候holder释放Canvas对象
PS:
欢迎大家关注我的微信公众号"大土豆爱开发",技术包括但不限于JavaEE,Android,Git等。