首页 > 代码库 > SurfaceView

SurfaceView

一、SurfaceView:可以在主线程之外的线程中向屏幕绘图。这样可以避免画图任务繁重的时候造成主线程阻塞,从而提高了程序的反应速度。

二、SurfaceView的使用

       首先继承SurfaceView并实现SurfaceHolder.Callback接口,

       这里注意:在绘制开始前要锁定画布及结束要解锁画布。SurfaceHolder.lockCanvas()、 SurfaceHolder.unlockCanvasAndPost(Canvas canvas)

三、实现一个正方形在屏幕内一直游动。

     SurfaceView视图代码:

public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback{
    private float x = 0;
    private float y = 0;
    private float speedx = 50;
    private float speedy = 50;
    private float addx = 2;
    private float addy = 2;
    private Paint mPaint = new Paint();
    private Timer mTimer;
    private TimerTask mTimerTask;
    public MySurfaceView(Context context) {
        super(context);

        //添加回调函数
        getHolder().addCallback(this);
        //画笔设置颜色
        mPaint.setColor(Color.BLUE);
    }
    //绘制方法
    public void draw(){
        //锁定画布
        Canvas canvas = getHolder().lockCanvas();
        canvas.drawColor(Color.WHITE);
        canvas.drawRect(x,y,speedx+x,speedy+y,mPaint);
        x += addx;
        y += addy;
        //边界的判断
        if(x<0){
            addx = Math.abs(addx);
        }
        if(y<0){
            addy = Math.abs(addy);
        }
        if(x>getWidth()-speedx){
            addx = -Math.abs(addx);
        }
        if(y>getHeight()-speedy){
            addy = -Math.abs(addy);
        }

        //解锁画布
        getHolder().unlockCanvasAndPost(canvas);
    }
    public void start(){
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                draw();
            }
        };
        mTimer.schedule(mTimerTask,1000,50);
    }
    public void stop(){
        mTimer.cancel();
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        stop();
    }
}

主活动加载SurfaceView视图代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MySurfaceView(this));
    }

 

SurfaceView