需求概述:
在屏幕上用手指画出一个区域,返回所圈的区域坐标。
技术实现:
自定义View,设置画笔及对应参数,在onTouchEvent()回调函数里,对触摸事件进行判断。画出矩形图形。
代码:
自定义View:
public class GameView extends View {
// 声明Paint对象
private Paint mPaint = null;
private int StrokeWidth = 5;
private Rect rect = new Rect(0,0,0,0);//手动绘制矩形 public GameView(Context context){
super(context);
//构建对象
mPaint = new Paint();
mPaint.setColor(Color.RED);
//开启线程
// new Thread(this).start();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//设置无锯齿
mPaint.setAntiAlias(true);
canvas.drawARGB(50,255,227,0);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(StrokeWidth);
mPaint.setColor(Color.GREEN);
mPaint.setAlpha(100);
// 绘制绿色实心矩形
canvas.drawRect(100, 200, 400, 200 + 400, mPaint);
mPaint.setColor(Color.RED);
canvas.drawRect(rect,mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
rect.right+=StrokeWidth;
rect.bottom+=StrokeWidth;
invalidate(rect);
rect.left = x;
rect.top = y;
rect.right =rect.left;
rect.bottom = rect.top; case MotionEvent.ACTION_MOVE:
Rect old =
new Rect(rect.left,rect.top,rect.right+StrokeWidth,rect.bottom+StrokeWidth);
rect.right = x;
rect.bottom = y;
old.union(x,y);
invalidate(old);
break; case MotionEvent.ACTION_UP:
break;
default:
break;
}
return true;//处理了触摸信息,消息不再传递
} }
调用时,只需要在onCreate()函数里,直接添加就可以:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); gameView = new GameView(this);
addContentView(gameView);
根据需要可以在自定义类中,加入返回圈定范围的函数。
ps:需要注意的是,在手指移动的时候,屏幕需要更新矩形时,原理上删除原来矩形,画上新矩形。但是由于空心矩形边厚度的存在,
会出现遗留的情况,此时要减去border厚度,可以解决上述问题。
Rect old = new Rect(rect.left,rect.top,rect.right+StrokeWidth,rect.bottom+StrokeWidth);