Convert from java.awt.geom.Area to java.awt.Polygon
I'm not sure if it's worth the conversion because Polygon is an old Java 1.0 class that can only store integer coordinates, so you might lose some precision. Either way, you can get the PathIterator from the Shape and, as you iterate through it, add new points to the Polygon:
public static void main(String[] args) {
Area a = new Area(new Rectangle(1, 1, 5, 5));
PathIterator iterator = a.getPathIterator(null);
float[] floats = new float[6];
Polygon polygon = new Polygon();
while (!iterator.isDone()) {
int type = iterator.currentSegment(floats);
int x = (int) floats[0];
int y = (int) floats[1];
if(type != PathIterator.SEG_CLOSE) {
polygon.addPoint(x, y);
System.out.println("adding x = " + x + ", y = " + y);
}
iterator.next();
}
}
EDIT As Bill Lin commented, this code can give you an incorrect polygon if the PathIterator describes multiple subpaths (for example, in the case of an area with holes). To take this into account, you also need to check for PathIterator.MOVETO segments and possibly create a polygon list.
To decide which polygons are holes, you can calculate the bounding rectangle (Shape.getBounds2D ()) and check which bounding rectangle contains the other. Note that the getBounds2D API says "there is no guarantee that the returned Rectangle2D is the smallest bounding rectangle that includes the Shape, only that the Shape lies entirely within the specified Rectangle2D", but in my experience, for polygonal shapes, this will be the smallest anyway, computing the exact bounding box of the polygon is trivial (just find the smallest and largest x and y coordinates).
source to share