SurfaceView extends View
其實(shí)View是在UI線程中進(jìn)行繪制
SurfaceView是在一個(gè)子線程中對自己進(jìn)行繪制,優(yōu)勢:避免造成UI線程阻塞
其實(shí)呢,我們SurfaceView中包含一個(gè)專門用于繪制的Surface,Surface中包含一個(gè)Canvas
如何獲得Canvas?
getHolder->SurfaceHolder
holder ->Canvas +管理SurfaceView的生命周期
surfaceCreated
surfaceChanged
surfaceDestroyed
Surface模板
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Created by TONG on 2017/3/22.
*/
public class SurfaceTemplate extends SurfaceView implements SurfaceHolder.Callback,Runnable {
private SurfaceHolder mHolder;
private Canvas mCanvas;
/**
* 用于繪制的線程
*/
private Thread t;
/**
* 線程的控制開關(guān)
*/
private boolean isRunning;
public SurfaceTemplate(Context context) {
this(context,null);
}
public SurfaceTemplate(Context context, AttributeSet attrs) {
super(context, attrs);
mHolder=getHolder();
mHolder.addCallback(this);
//獲得焦點(diǎn)
setFocusable(true);
setFocusableInTouchMode(true);
//設(shè)置常量
setKeepScreenOn(true);
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
isRunning=true;
t=new Thread(this);
t.start();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
isRunning=false;
}
@Override
public void run() {
//不斷進(jìn)行繪制
while (isRunning){
draw();
}
}
private void draw() {
try {
mCanvas=mHolder.lockCanvas();
if(mCanvas!=null){
//draw something
}
} catch (Exception e) {
}finally {
if(mCanvas!=null)
{
mHolder.unlockCanvasAndPost(mCanvas);
}
}
}
}