SurfaceView
1.SurfaceView与View的区别
-SurfaceView可以主动更新,可以频繁的刷新。
-View在主线程进行刷新,而SurfaceView在子线程中进行刷新(可在刷新时处理大量数据)。
-SurfaceView实现了双缓冲机制?
2.创建SurfaceView
继承SurfaceView,实现两个接口——SurfaceHolder.Callback和Runnable。
3.初始化
private SurfaceHolder mHolder;
private boolean mIsDrawing;//子线程标志位,用来控制子线程
private Canvas mCanvas;
初始化SurfaceHolder
mHolder=getHolder();
mHolder.addCallback(this);
3.Canvas相关的方法
获取Canvas:lockCanvas();
擦除Canvas:drawColor(Color.WHITE);
提交内容:unlockCanvasAndPost(mCanvas);
4.基础代码
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback,Runnable {
private SurfaceHolder mHolder;
private boolean mIsDrawing;
private Canvas mCanvas;
public MySurfaceView(Context context) {
super(context);
initView(context);
}
public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
private void initView(Context context) {
mHolder = getHolder();
mHolder.addCallback(this);
setFocusable(true);//?
setFocusableInTouchMode(true);//?
this.setKeepScreenOn(true);//?
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mIsDrawing = true;
new Thread(this).start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mIsDrawing = false;
}
@Override
public void run() {
while(mIsDrawing){
draw();
}
}
private void draw() {
try{
mCanvas = mHolder.lockCanvas();
//这里使用mCanvas.draw...
}catch (Exception e){
}finally {
if(mCanvas!=null){
mHolder.unlockCanvasAndPost(mCanvas);//提交内容
}
}
}
}