实现自定义View,SurfaceView的基本框架

public class BackGround extends SurfaceView implements SurfaceHolder.Callback{

    Canvas canvas;
    Paint paint = new Paint();
    DoDrawThread doDrawThread;

    public Button(Context context) {
        super(context);
        getHolder().addCallback(this);
        doDrawThread = new DoDrawThread(getHolder());
        canvas = new Canvas();
    }

    public void doDraw(Canvas canvas){
        canvas.drawColor(Color.WHITE);
        ...
    }


    class DoDrawThread extends Thread{
        boolean flag = true;
        SurfaceHolder surfaceHolder;
        Canvas canvas = new Canvas();

        DoDrawThread(SurfaceHolder holder){
            this.surfaceHolder = holder;
        }

        @Override
        public void run() {
            while (flag) {
                canvas = null;
                try {
                    // 锁定整个画布,在内存要求比较高的情况下,建议参数不要为null
                    canvas = this.surfaceHolder.lockCanvas(null);
                    doDraw(canvas);
//                  }
                } finally {
                    if (canvas != null) {
                        //更新屏幕显示内容
                        this.surfaceHolder.unlockCanvasAndPost(canvas);
                    }
                }
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!doDrawThread.isAlive()){
            doDrawThread.start();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }
}

你可能感兴趣的:(Andriod)