Android应用:自定义SurfaceView

自定义View类,实现绘制一个随鼠标拖动的矩形。

1、创建一个MySurfaceView类

public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
    private Paint mPaint;
    int widthPixels;
    int heightPixels;
    float cx, cy;
 
    SurfaceHolder mSurfaceHolder;
    Thread thread;
 
    public MeasureView(Context context) {
        super(context);
 
        mSurfaceHolder = this.getHolder();
        mSurfaceHolder.addCallback(this);
 
        mPaint = new Paint();
        thread = new Thread(this);
    }
 
    public void draw() {
        Canvas canvas = mSurfaceHolder.lockCanvas();
 
        if (mPaint == null || canvas == null) return;
 
        mPaint.setAntiAlias(true);
        //用白色清屏
        canvas.drawColor(Color.WHITE);
 
        mPaint.setColor(Color.BLACK);
        //根据鼠标位置画一个矩形
        canvas.drawRect(cx,cy,100,100,mPaint);
        mSurfaceHolder.unlockCanvasAndPost(canvas);
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                //获取鼠标位置
                cx = event.getX();
                cy = event.getY();
                break;
        }
        return true;
    }
 
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        //获取屏幕尺寸
        widthPixels = getWidth();
        heightPixels = getHeight();
        //启动线程
        thread.start();
    }
 
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
 
    }
 
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }
 
    @Override
    public void run() {
        //每100ms重绘一次
        while (true) {
            try {
                draw();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2、在activity中引用这个类
setContentView(new MeasureView(this)); 

你可能感兴趣的:(android)