简体   繁体   中英

Convert from java.awt.geom.Area to java.awt.Polygon

I need to convert a java.awt.geom.Area or java.awt.Shape to java.awt.Polygon . What I know about the are is: isSingular = true , isPolygonal = true . So I think a polygon shuld be able to describe the same area.

I'm not sure that it is worth converting, because Polygon is an old Java 1.0 class that can store only integer coordinates, so you might lose some precision. Anyway, you can get a PathIterator from the Shape, and as you iterate it, add new points to a 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 may give you a wrong polygon if the PathIterator describes multiple subpaths (for example in the case of an Area with holes). In order to take this into account, you also need to check for PathIterator.MOVETO segments, and possibly create a list of polygons.

In order to decide which polygons are holes, you could calculate the bounding box (Shape.getBounds2D()), and check which bounding box contains the other. Note that the getBounds2D API says that "there is no guarantee that the returned Rectangle2D is the smallest bounding box that encloses the Shape, only that the Shape lies entirely within the indicated Rectangle2D", but in my experience for polygonal shapes it would be the smallest, and anyway it is trivial to calculate the exact bounding box of a polygon (just find the smallest and biggest x and y coordinates).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM