Android: How to determine if a touch event is in a circle?

前端 未结 2 624
暖寄归人
暖寄归人 2021-02-01 10:40

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?

So far I extend a view and imple

相关标签:
2条回答
  • 2021-02-01 10:50

    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.

    Values explanation is:

    (x + radius) and (y + radius) is the center of circle.

    (xTouch - (x + radius)) is distance from touch point to center by X.

    (yTouch - (y + radius)) is distance from touch point to center by Y.

    0 讨论(0)
  • 2021-02-01 11:11

    Another way to do this, and a little simpler I think, is to use the distance between two points formula and compare that distance to your radius. If the calculated distance is less than the radius then the touch is inside your circle.

    Here the code

    // Distance between two points formula
    float touchRadius = (float) Math.sqrt(Math.pow(touchX - mViewCenterPoint.x, 2) + Math.pow(touchY - mViewCenterPoint.y, 2));
    
    if (touchRadius < mCircleRadius)
    {
        // TOUCH INSIDE THE CIRCLE!
    }
    
    0 讨论(0)
提交回复
热议问题