一、SurfaceView认识及的应用的思路
- SurfaceView继承自(extends)View,View是在UI线程中进行绘制;
- 而SurfaceView是在一个子线程中对自己进行绘制,优势:避免造成UI线程阻塞;
- SurfaceView中包含一个专门用于绘制的Surface,Surface中包含一个Canvas;
- 获得Canvas:可以从SurfaceView中方法的getHolder()获得SurfaceHolder,从holder获得Canvas;
- holder还管理着SurfaceView的生命周期:
①surfaceCreated()创建子线程,子线程的run()方法中开启SurfaceView的绘制。
②surfaceChanged()。
③surfaceDestoryed()中关闭子线程。
二、SurfaceView的一般写法
1 package com.example.luckypan; 2 3 import android.content.Context; 4 import android.graphics.Canvas; 5 import android.util.AttributeSet; 6 import android.view.SurfaceHolder; 7 import android.view.SurfaceHolder.Callback; 8 import android.view.SurfaceView; 9 10 public class SurfaceViewTemplate extends SurfaceView implements Callback, Runnable { 11 12 private SurfaceHolder mHolder; 13 private Canvas mCanvas; 14 /** 15 * 用于绘制线程 16 */ 17 private Thread thread; 18 /** 19 * 线程的控制开关 20 */ 21 private boolean isRunning; 22 public SurfaceViewTemplate(Context context) { 23 this(context, null); 24 } 25 public SurfaceViewTemplate(Context context, AttributeSet attrs) { 26 super(context, attrs); 27 mHolder=getHolder(); 28 mHolder.addCallback(this); 29 //可获得焦点 30 setFocusable(true); 31 setFocusableInTouchMode(true); 32 //设置常量 33 setKeepScreenOn(true); 34 } 35 public void surfaceCreated(SurfaceHolder holder) { 36 isRunning=true; 37 thread=new Thread(this); 38 thread.start(); 39 40 } 41 public void surfaceChanged(SurfaceHolder holder, int format, int width, 42 int height) { 43 // TODO Auto-generated method stub 44 45 } 46 public void surfaceDestroyed(SurfaceHolder holder) { 47 isRunning=false; 48 49 } 50 public void run() { 51 //不断进行绘制 52 while (isRunning) 53 { 54 draw(); 55 } 56 } 57 private void draw() { 58 try { 59 mCanvas=mHolder.lockCanvas(); 60 if (mCanvas!=null) { 61 // 62 } 63 } 64 catch (Exception e) { 65 66 } 67 finally 68 { 69 if (mCanvas!=null) { 70 mHolder.unlockCanvasAndPost(mCanvas); 71 } 72 } 73 } 74 75 76 }