我想使用Java的Area类(java.awt.geom.Area)在各种多边形上执行减法和交集操作.
在许多这些情况下,减法操作可以将源区域分成两部分.在这些情况下,我需要返回两个Area对象,一个用于由减法操作创建的每个结果连续部分.
在阅读了Area类的JavaDocs之后,我似乎没有找到任何方法来返回Area的连续部分.事实上,我甚至不确定Area如何处理这种情况.
如何通过Area的减法或交叉方法获得所有生成的连续区域?
谢谢,
-Cody
解决方法:
正如我在评论中所说.迭代轮廓路径,获得绕组并识别段起点.当您点击PathIterator.SEG_MOVETO构造一个java.awt.Path2D.Float并向其添加点,直到您点击PathIterator.SEG_CLOSE.
这是我为你演示的一个例子
public static List<Area> getAreas(Area area) {
PathIterator iter = area.getPathIterator(null);
List<Area> areas = new ArrayList<Area>();
Path2D.Float poly = new Path2D.Float();
Point2D.Float start = null;
while(!iter.isDone()) {
float point[] = new float[2]; //x,y
int type = iter.currentSegment(point);
if(type == PathIterator.SEG_MOVETO) {
poly.moveTo(point[0], point[1]);
} else if(type == PathIterator.SEG_CLOSE) {
areas.add(new Area(poly));
poly.reset();
} else {
poly.lineTo(point[0],point[1]);
}
iter.next();
}
return areas;
}
public static void main(String[] args) {
Area a = new Area(new Polygon(new int[]{0,1,2}, new int[]{2,0,2}, 3));
Area b = new Area(new Polygon(new int[]{0,2,4}, new int[]{0,2,0}, 3));
b.subtract(a);
for(Area ar : getAreas(b)) {
PathIterator it = ar.getPathIterator(null);
System.out.println("New Area");
while(!it.isDone()) {
float vals[] = new float[2];
int type = it.currentSegment(vals);
System.out.print(" " + "[" + vals[0] + "," + vals[1] +"]");
it.next();
}
System.out.println();
}
}