我需要将java.awt.geom.Area或java.awt.Shape转换为java.awt.Polygon 。 我所知道的是: isSingular = true , isPolygonal = true 。 所以我认为多边形可以描述相同的区域。
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.
最满意答案
我不确定它是否值得转换,因为Polygon是一个旧的Java 1.0类,只能存储整数坐标,所以你可能会失去一些精度。 无论如何,您可以从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(); } }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).
更多推荐
发布评论