Android之SurfaceView

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);//提交内容
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值