Home > Java, Useful stuff > Detect if point is in a rectangle / polygon

Detect if point is in a rectangle / polygon

This checks to see if a point x,y is within a rectangle or polygon defined by an array of coordinates co. The coordinate class is based on the Point class that comes with Java - just a simple x and y. This will assume all the points are contiguous. It was coded for use in J2ME, but depending on what version you are using you may have to replace the use of doubles for something MIDP1 can handle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
boolean pointInRect(double x,double y,Coordinate [] co){
    int j=(co.length-1);
    boolean inFlag = false;
    for(int i=0;i<co.length;i++){
        if (((((double)co[i].getY() <= y) && 
           (y < (double)co[j].getY())) ||
           (((double)co[j].getY() <= y) && 
           (y < (double)co[i].getY()))) &&
           (x < ((double)co[j].getX() - (double)co[i].getX()) * 
           (y - (double)co[i].getY()) / ((double)co[j].getY() -
           (double)co[i].getY()) + (double)co[i].getX()))
                inFlag = !inFlag;
        j = i;
    }
    return inFlag;
}

This is based off a piece of VB code I found somewhere on a Math forum ( where people exist that are brainier than me )

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Google] [StumbleUpon]

Java, Useful stuff

  1. No comments yet.
  1. No trackbacks yet.