需求概述: 在屏幕上用手指画出一个区域,返回所圈的区域坐标。 技术实现: 自定义View,设置画笔及对应参数,在onTouchEvent()回调函数里,对触摸事件进行判断。画出矩形图形。 代码: 自定义View: 1 public class GameView exte ...
需求概述:
在屏幕上用手指画出一个区域,返回所圈的区域坐标。
技术实现:
自定义View,设置画笔及对应参数,在onTouchEvent()回调函数里,对触摸事件进行判断。画出矩形图形。
代码:
自定义View:
1 public class GameView extends View { 2 // 声明Paint对象 3 private Paint mPaint = null; 4 private int StrokeWidth = 5; 5 private Rect rect = new Rect(0,0,0,0);//手动绘制矩形 6 7 public GameView(Context context){ 8 super(context); 9 //构建对象10 mPaint = new Paint();11 mPaint.setColor(Color.RED);12 //开启线程13 // new Thread(this).start();14 }15 @Override16 protected void onDraw(Canvas canvas) {17 super.onDraw(canvas);18 //设置无锯齿19 mPaint.setAntiAlias(true);20 canvas.drawARGB(50,255,227,0);21 mPaint.setStyle(Paint.Style.STROKE);22 mPaint.setStrokeWidth(StrokeWidth);23 mPaint.setColor(Color.GREEN);24 mPaint.setAlpha(100);25 // 绘制绿色实心矩形26 canvas.drawRect(100, 200, 400, 200 + 400, mPaint);27 mPaint.setColor(Color.RED);28 canvas.drawRect(rect,mPaint);29 }30 @Override31 public boolean onTouchEvent(MotionEvent event) {32 int x = (int)event.getX();33 int y = (int)event.getY();34 switch (event.getAction()){35 case MotionEvent.ACTION_DOWN:36 rect.right+=StrokeWidth;37 rect.bottom+=StrokeWidth;38 invalidate(rect);39 rect.left = x;40 rect.top = y;41 rect.right =rect.left;42 rect.bottom = rect.top;43 44 case MotionEvent.ACTION_MOVE:45 Rect old =46 new Rect(rect.left,rect.top,rect.right+StrokeWidth,rect.bottom+StrokeWidth);47 rect.right = x;48 rect.bottom = y;49 old.union(x,y);50 invalidate(old);51 break;52 53 case MotionEvent.ACTION_UP:54 break;55 default:56 break;57 }58 return true;//处理了触摸信息,消息不再传递59 }60 61 }
原标题:Android 通过触摸动态地在屏幕上画矩形
关键词:Android
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。