SurfaceView是一个专门用于做频繁绘制的View子类,它的绘制操作是在子线程中执行,所以频繁绘制不会阻塞线程,使用它去做一些需要频繁绘制和长时间绘制效果会高很多。而如果这种操作放入到View中去做的话就不合适了,首先View的刷新UI操作都是需要在UI线程中,也就是我们的主线程中。如果去执行一些需要长时间绘制,就会造成UI阻塞造成无法响应其他时间
使用过程
surfaceCreated
创建时调用,如果View隐藏或者activity onResume方法也会重新调用。
surfaceChanged
surfaceCreated 后调用
surfaceDestroyed
view隐藏或者销毁时调用
SurfaceHolder mHolder = getHolder();
获取一个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);
}
}
网友评论