javageometrypolygonarea

How to implement Area.contains(Area)?


There are 2 areas (java.awt.geom.Area) area1 and area2. I need to verify if area2 is inside area1? (area1 contains area2).

I have tried:

areaDelta = (Area)area1.clone();
areaDelta.add(area2);
return areaDelta.equals(area1);

But it doesnt always work as it should (If the bounds of area2 are on the bounds of area1, it returns true, should return false).

In fact I have 2 polygons (java.awt.Polygon) and I need the Polygon.contains(Polygon) method, may be this can be easier then for areas.

Any ideas?

Polygons can be convex and non-convex.


Solution

  • Since you have Polygon.contains(Point), you can achieve what you need by testing if every point of your second polygon is inside the first polygon (I dream of a JDK version which would implement every basic need of a programmer, like .NET).

    EDIT: To handle concave polygons, you first need to split your polygons into convex ones, then you'll be able to properly use the method mentioned above. I used two different polygon decomposition algorithms in one of my applications, and I would suggest you to look at their code: