我們都知道,一個圓形的ImageView控件(本項目中使用的圓形控件是github上的),其實所占的區域還是正方形區域,只是顯示內容為圓形,當我們給ImageView設置觸摸事件時,沒有顯示區域也會相應點擊事件,而我們可以通過計算當前點擊的位置來判斷ImageView是否相應觸摸事件。
效果如圖所示:
如上圖所示,當點擊圓之內拖動時,圓跟著移動,但是點擊圓之外拖動時,圓沒有任何反應。
要實現這個效果并不難,首先,先計算出圓的中心點坐標(x1,y1),注意,x1,y1是相對于屏幕的坐標,不是相對于布局的坐標;
然后獲取當前按下的坐標(x2,y2),只需要計算出當前按下的點的坐標(x2,y2)與圓心(x1,y1)的距離d的長度,然后與圓的半徑r相比較,如果d>r則當前按下的點在圓之外,如果d<r,則當前按下的點在圓之內, 如下圖所示:
這樣注意一下,以上都應在MotionEvent.ACTION_DOWN里面計算,當距離d大于半徑r時,return false,則當前控件不消費事件,
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
public class MainActivity extends Activity { int lastX; int lastY; boolean isView = false ; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); final CircleImageView civ = (CircleImageView) findViewById(R.id.civ_levitate); civ.setOnTouchListener( new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: lastX = ( int ) event.getRawX(); lastY = ( int ) event.getRawY(); //獲取控件在屏幕的位置 int [] location = new int [ 2 ]; civ.getLocationOnScreen(location); //控件相對于屏幕的x與y坐標 int x = location[ 0 ]; int y = location[ 1 ]; //圓半徑 通過左右坐標計算獲得getLeft int r = (civ.getRight()-civ.getLeft())/ 2 ; //圓心坐標 int vCenterX = x+r; int vCenterY = y+r; //點擊位置x坐標與圓心的x坐標的距離 int distanceX = Math.abs(vCenterX-lastX); //點擊位置y坐標與圓心的y坐標的距離 int distanceY = Math.abs(vCenterY-lastY); //點擊位置與圓心的直線距離 int distanceZ = ( int ) Math.sqrt(Math.pow(distanceX, 2 )+Math.pow(distanceY, 2 )); //如果點擊位置與圓心的距離大于圓的半徑,證明點擊位置沒有在圓內 if (distanceZ > r){ return false ; } isView = true ; break ; case MotionEvent.ACTION_MOVE: if (isView){ int moveX = ( int ) event.getRawX(); int moveY = ( int ) event.getRawY(); int disX = moveX - lastX; int disY = moveY - lastY; int left = civ.getLeft()+disX; int right = civ.getRight()+disX; int top = civ.getTop()+disY; int bottom = civ.getBottom()+disY; civ.layout(left,top,right,bottom); lastX = moveX; lastY = moveY; } break ; case MotionEvent.ACTION_UP: isView = false ; break ; } return true ; } }); } } |
好了,demo下載地址:點擊下載
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/fan7983377/article/details/51262383