美学原理Android 通过动动态地于屏幕及绘矩形

  需求概述:

  于屏幕上就此手指画出一个区域,返回所环绕的区域坐标。

  技术实现:

  自定义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     @Override
16     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     @Override
31     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 }

调用时,只待在onCreate()函数里,直接助长就好:

1         super.onCreate(savedInstanceState);
2         setContentView(R.layout.activity_main);
3 
4         gameView = new GameView(this);
5         addContentView(gameView);        

冲需要好以从定义类中,加入返回圈定范围之函数。

ps:需要专注的凡,在指运动的时节,屏幕需要更新矩形时,原理及勾原来矩形,画上新矩形。但是由于空心矩形边厚度的存,

会见油然而生遗留的情形,此时如果减去border厚度,可以缓解上述问题。

Rect old = new Rect(rect.left,rect.top,rect.right+StrokeWidth,rect.bottom+StrokeWidth);

 效果图:

美学原理 1