SurfaceView是一個(gè)專門用于做頻繁繪制的View子類,它的繪制操作是在子線程中執(zhí)行估盘,所以頻繁繪制不會(huì)阻塞線程,使用它去做一些需要頻繁繪制和長(zhǎng)時(shí)間繪制效果會(huì)高很多。而如果這種操作放入到View中去做的話就不合適了它改,首先View的刷新UI操作都是需要在UI線程中,也就是我們的主線程中商乎。如果去執(zhí)行一些需要長(zhǎng)時(shí)間繪制央拖,就會(huì)造成UI阻塞造成無法響應(yīng)其他時(shí)間
使用過程
surfaceCreated
創(chuàng)建時(shí)調(diào)用,如果View隱藏或者activity onResume方法也會(huì)重新調(diào)用鹉戚。
surfaceChanged
surfaceCreated 后調(diào)用
surfaceDestroyed
view隱藏或者銷毀時(shí)調(diào)用
SurfaceHolder mHolder = getHolder();
獲取一個(gè)holder獲取canvas和提交canvas
Canvas canvas = mHolder.lockCanvas();
獲取canvas做繪制操作
mHolder.unlockCanvasAndPost(canvas);
提交繪制操作
public class DrawingBoardView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
public DrawingBoardView(Context context) {
this(context, null);
}
public DrawingBoardView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawingBoardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void initData() {
mHolder = getHolder();
getBackground().setAlpha(127);
setZOrderMediaOverlay(true);
setZOrderOnTop(true);
mHolder.setFormat(PixelFormat.TRANSLUCENT);
mHolder.unlockCanvasAndPost(canvas);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mIsRuning = false;
}
@Override
public void run() {
}
private void drawPattern(int x, int y) {
//繪制過程
Canvas canvas = mHolder.lockCanvas();
Canvas newCanvas = new Canvas(mDrawBitmap);
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas.drawBitmap(mDrawBitmap, 0, 0, mPaint);
mHolder.unlockCanvasAndPost(canvas);
}
}