J. Lev
J. Lev

Reputation: 317

Contains method doesn't seem to work with a point inside my polygon

I am trying to add a functionnality which would let me see if a point is inside a polygon.

Here's the code snippet to see if the point is inside my polygon

int x = 265;
int y = 300;
List<Point> points = new ArrayList<Point>(); 

points.add(new Point(233,155));
points.add(new Point(347,269));
points.add(new Point(136,251));
points.add(new Point(250,366));

Polygon polygon = new Polygon();//java.awt.Polygon

for(Point point : points) {
    polygon.addPoint(point.x, point.y);
}

return polygon.contains(x,y);

The code seems to work if my point is closer to the upper-left side of the polygon, however when the point is on the bottom-right side, the method contains will return false.

Graph of my polygon and the point in question : https://www.desmos.com/calculator/tnglrdpivn

Any idea why this happens ?

Upvotes: 1

Views: 467

Answers (1)

Krease
Krease

Reputation: 16225

The key here is in the ordering of your points. Though plotted all at once on a graph, they look like they form a nice looking polygon, if you play connect-the-dots with them in the order you add them to the polygon, they form a very weird shape, and the point is really not contained in the polygon.

If you reverse the order of your last two points, the connect-the-dots polygon is properly formed, and then the point is contained in the polygon.

Upvotes: 2

Related Questions