从 java.awt.geom.Area 转换为 java.awt.Polygon
Convert from java.awt.geom.Area to java.awt.Polygon
我需要将 java.awt.geom.Area
或 java.awt.Shape
转换为 java.awt.Polygon
。我所知道的是:isSingular = true
、isPolygonal = true
。所以我认为多边形应该能够描述相同的区域。
我不确定它是否值得转换,因为 Polygon 是旧的 Java 1.0 class,它只能存储整数坐标,因此您可能会失去一些精度。
无论如何,您可以从 Shape 中获取 PathIterator,并在迭代它时向多边形添加新点:
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();
}
}
编辑 正如 Bill Lin 评论的那样,如果 PathIterator 描述了多个子路径(例如,在有孔的区域的情况下),此代码可能会给您一个错误的多边形。为了考虑到这一点,您还需要检查 PathIterator.MOVETO 段,并可能创建一个多边形列表。
为了确定哪些多边形是洞,您可以计算边界框(Shape.getBounds2D()),并检查哪个边界框包含另一个边界框。请注意 getBounds2D API 表示 "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",但根据我对多边形形状的经验,它将是最小的,无论如何计算多边形的精确边界框是微不足道的(只需找到最小的和最大的 x 和 y 坐标)。
我需要将 java.awt.geom.Area
或 java.awt.Shape
转换为 java.awt.Polygon
。我所知道的是:isSingular = true
、isPolygonal = true
。所以我认为多边形应该能够描述相同的区域。
我不确定它是否值得转换,因为 Polygon 是旧的 Java 1.0 class,它只能存储整数坐标,因此您可能会失去一些精度。 无论如何,您可以从 Shape 中获取 PathIterator,并在迭代它时向多边形添加新点:
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();
}
}
编辑 正如 Bill Lin 评论的那样,如果 PathIterator 描述了多个子路径(例如,在有孔的区域的情况下),此代码可能会给您一个错误的多边形。为了考虑到这一点,您还需要检查 PathIterator.MOVETO 段,并可能创建一个多边形列表。
为了确定哪些多边形是洞,您可以计算边界框(Shape.getBounds2D()),并检查哪个边界框包含另一个边界框。请注意 getBounds2D API 表示 "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",但根据我对多边形形状的经验,它将是最小的,无论如何计算多边形的精确边界框是微不足道的(只需找到最小的和最大的 x 和 y 坐标)。