我們都知道,一個(gè)圓形的ImageView控件(本項(xiàng)目中使用的圓形控件是github上的),其實(shí)所占的區(qū)域還是正方形區(qū)域,只是顯示內(nèi)容為圓形,當(dāng)我們給ImageView設(shè)置觸摸事件時(shí),沒有顯示區(qū)域也會(huì)相應(yīng)點(diǎn)擊事件,而我們可以通過計(jì)算當(dāng)前點(diǎn)擊的位置來判斷ImageView是否相應(yīng)觸摸事件。
效果如圖所示:
如上圖所示,當(dāng)點(diǎn)擊圓之內(nèi)拖動(dòng)時(shí),圓跟著移動(dòng),但是點(diǎn)擊圓之外拖動(dòng)時(shí),圓沒有任何反應(yīng)。
要實(shí)現(xiàn)這個(gè)效果并不難,首先,先計(jì)算出圓的中心點(diǎn)坐標(biāo)(x1,y1),注意,x1,y1是相對(duì)于屏幕的坐標(biāo),不是相對(duì)于布局的坐標(biāo);
然后獲取當(dāng)前按下的坐標(biāo)(x2,y2),只需要計(jì)算出當(dāng)前按下的點(diǎn)的坐標(biāo)(x2,y2)與圓心(x1,y1)的距離d的長(zhǎng)度,然后與圓的半徑r相比較,如果d>r則當(dāng)前按下的點(diǎn)在圓之外,如果d<r,則當(dāng)前按下的點(diǎn)在圓之內(nèi), 如下圖所示:
這樣注意一下,以上都應(yīng)在MotionEvent.ACTION_DOWN里面計(jì)算,當(dāng)距離d大于半徑r時(shí),return false,則當(dāng)前控件不消費(fèi)事件,
代碼如下:
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); //控件相對(duì)于屏幕的x與y坐標(biāo) int x = location[ 0 ]; int y = location[ 1 ]; //圓半徑 通過左右坐標(biāo)計(jì)算獲得getLeft int r = (civ.getRight()-civ.getLeft())/ 2 ; //圓心坐標(biāo) int vCenterX = x+r; int vCenterY = y+r; //點(diǎn)擊位置x坐標(biāo)與圓心的x坐標(biāo)的距離 int distanceX = Math.abs(vCenterX-lastX); //點(diǎn)擊位置y坐標(biāo)與圓心的y坐標(biāo)的距離 int distanceY = Math.abs(vCenterY-lastY); //點(diǎn)擊位置與圓心的直線距離 int distanceZ = ( int ) Math.sqrt(Math.pow(distanceX, 2 )+Math.pow(distanceY, 2 )); //如果點(diǎn)擊位置與圓心的距離大于圓的半徑,證明點(diǎn)擊位置沒有在圓內(nèi) 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下載地址:點(diǎn)擊下載
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/fan7983377/article/details/51262383