SurfaceView常用于需要频繁刷新,或者刷新时需要大量的数据处理,在新线程绘制和处理。虽然,SurfaceView用法相对于View来说比较复杂,但是SufaceView使用时,有一套使用的模板代码,大部分SurfaceView绘图操作都可以套用这样的模板代码来编写。
public class SurfaceViewTemplate extends SurfaceView implements
SurfaceHolder.Callback, Runnable {
//SurfaceHolder
private SurfaceHolder mHolder;
//用于绘制的Canvas
private Canvas mCanvas;
//子线程标志位
private boolean mIsDrawing;
public SurfaceViewTemplate(Context context) {
super(context);
initView();
}
public SurfaceViewTemplate(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public SurfaceViewTemplate(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
/**
* 初始化对象
*/
private void initView(){
mHolder = getHolder();
mHolder.addCallback(this);
setFocusable(true);
setFocusableInTouchMode(true);
this.setKeepScreenOn(true);
}
/**
* 通过子线程进行绘制
*/
@Override
public void run() {
while(mIsDrawing){
draw();
}
}
/**
* 进行绘制
*/
private void draw(){
try{
mCanvas = mHolder.lockCanvas();
}catch(Exception e){
}finally{
if(mCanvas != null){
mHolder.unlockCanvasAndPost(mCanvas);
}
}
}
/**
* SurfaceView的改变
*/
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
/**
* SurfaceView的创建
*/
@Override
public void surfaceCreated(SurfaceHolder holder) {
mIsDrawing = true;
new Thread(this).start();
}
/**
* SurfaceView的销毁
*/
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mIsDrawing = false;
}
} ````