Android:如何确定触摸事件是否在圈中? [英] Android: How to determine if a touch event is in a circle?
问题描述
我想在触摸圆形区域时播放媒体,但是如何确定触摸位置在圆圈中呢?
I want to play a media when i touch a circular area, but how can I could determine that my touch position is in the circle?
到目前为止,我扩展了view
并实现了onTouchEvent
,并且我需要一种算法来确定位置是在圆内还是圆外.
So far I extend a view
and implement the onTouchEvent
, and I need the algorithm for deciding if the position is inside or outside the circle.
推荐答案
您应该使用 View.getY()以获得左上角的x
和y
,并且还假设您知道半径(或能够获取视图的宽度/高度确定半径).之后,使用 MotionEvent获取xTouch
和yTouch
.getX()和 MotionEvent.getY( ),并检查是否:
You should take position of the view with View.getX() and View.getY() to get x
and y
of the upper left corner and also assuming You know the radius (or able to obtain width/height of the view to determine radius). After that, obtain xTouch
and yTouch
using MotionEvent.getX() and MotionEvent.getY() and check if:
double centerX = x + radius;
double centerY = y + radius;
double distanceX = xTouch - centerX;
double distanceY = yTouch - centerY;
boolean isInside() {
return (distanceX * distanceX) + (distanceY * distanceY) <= radius * radius;
}
该公式只是对学校几何形状的解释,以确定点是否在圆形区域内.有关更多详细信息,请参考笛卡尔坐标系的圆方程.
The formula is just interpretation of schools geometry for determining if dot is inside circle area or not. Refer to circle equation for Cartesian coordinates for more details.
值的解释是:
(x + radius)
和(y + radius)
是圆的中心.
(xTouch - (x + radius))
是触摸点到中心的距离X.
(xTouch - (x + radius))
is distance from touch point to center by X.
(yTouch - (y + radius))
是触摸点到中心的距离,以Y为单位.
(yTouch - (y + radius))
is distance from touch point to center by Y.
这篇关于Android:如何确定触摸事件是否在圈中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!