开发者

How to detect which rectangle was clicked?

开发者 https://www.devze.com 2023-02-10 14:33 出处:网络
I have several rectangular shapes on my screen, some of them rotated. Now the user clicks on a position(x,y开发者_开发问答) ofthe screen. Is there a standard algorithm to detect which of the rectangle

I have several rectangular shapes on my screen, some of them rotated. Now the user clicks on a position(x,y开发者_开发问答) ofthe screen. Is there a standard algorithm to detect which of the rectangle(s) was clicked(contains the (x,y) coordinates)?

This is related to a problem I'm having: Child Views that are translated, scaled or rotated disappear


If you search for "point in polygon algorithms" you'll find a bunch. For rectangles, I guess that the easiest is to divide the rectangle into two triangles and check the test point's barycentric coordinates. Here's an untested off-the-cuff attempt to code it up:

boolean pointInTriangle(int x, int y, int x1, int y1, int x2, int y2, int x3, int y3) {
    int denom = (y2-y3)*(x1-x3) + (x3-x2)*(y1-y3);
    if(denom==0) return false; // collinear

    int num1 = (y2-y3)*(x-x3) + (x3-x2)*(y-y3);
    if((denom < 0 && num1 > 0) || (denom > 0 && num1 < 0)) return false;

    int num2 = (y3-y1)*(x-x3) + (x1-x3)*(y-y3);
    if((denom < 0 && num2 > 0) || (denom > 0 && num2 < 0)) return false;

    int num3 = denom - num1 - num2;
    if((denom < 0 && num3 > 0) || (denom > 0 && num3 < 0)) return false;

    return true;
}

Now you just have to loop over your rectangles, checking whether the point is in either of two triangles which make up the rectangle.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号