简体   繁体   English

从java.awt.geom.Area转换为java.awt.Polygon

[英]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 . 我需要将java.awt.geom.Areajava.awt.Shape转换为java.awt.Polygon What I know about the are is: isSingular = true , isPolygonal = true . 我所知道的是: isSingular = trueisPolygonal = 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. 我不确定它是否值得转换,因为Polygon是一个旧的Java 1.0类,只能存储整数坐标,所以你可能会失去一些精度。 Anyway, you can get a PathIterator from the Shape, and as you iterate it, add new points to a Polygon: 无论如何,您可以从Shape获取PathIterator,并在迭代它时,向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). 编辑正如Bill Lin评论的那样,如果PathIterator描述了多个子路径,则此代码可能会给出错误的多边形(例如,在带有孔的区域的情况下)。 In order to take this into account, you also need to check for PathIterator.MOVETO segments, and possibly create a list of polygons. 为了考虑到这一点,您还需要检查PathIterator.MOVETO段,并可能创建多边形列表。

In order to decide which polygons are holes, you could calculate the bounding box (Shape.getBounds2D()), and check which bounding box contains the other. 为了确定哪些多边形是空洞,您可以计算边界框(Shape.getBounds2D()),并检查哪个边界框包含另一个边界框。 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). 请注意,getBounds2D API表示“无法保证返回的Rectangle2D是包含Shape的最小边界框,只有Shape完全位于指定的Rectangle2D内”,但根据我对多边形形状的体验,它将是最小的,无论如何,计算多边形的精确边界框(只找到最小和最大的x和y坐标)是微不足道的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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