Search code examples
androidtouchhittest

What's the best way of doing hit test for irregular-shaped controls in Android?


I am going to implement a customized shape of control like a D-PAD for my Android application.

enter image description here

As you can see from the picture, there are 5 control buttons. But everyone knows that a view's touch area is a rectangle. My target is to fire the correct touch event when user is touch inside the visible bounds of each control.

My primitive idea is to intercept the touch event and do some pure geometric computation. But I found it is somehow every complicated and not seem a good way to solve this problem.

Is there anyone could give me some inspiration?


Solution

  • There is not a function that allows you to do that. Either you slice your shapes in simple geometrical sections and test, or maybe you can use the technique with a bitmap mask described in this link.

    EDIT:

    1. Translate both the click point and the center of your circle to the origin
    2. Calculate the radius of the click point sqrt(x^2 + y^2)
    3. If the radius is greater than the radius of the inner circle and less than the outer radius... continue
    4. Calculate the angle arctan(y/x) to get which one of the four buttons was hit.