Reputation: 2732
I want to use Java's Area class (java.awt.geom.Area) to preform subtraction and intersection operations on various polygons.
In many of these cases the subtraction operation may split the source Area into two. In these cases I need to have two Area objects returned, one for each of the resulting contiguous sections created by the subtraction operation.
After reading through the JavaDocs on the Area class I haven't seemingly found any way to return a contiguous part of the Area. In fact I'm not even sure how Area handles such a situation.
How would I get all of the resulting contiguous Area's created by Area's subtraction or intersection methods?
Thanks, -Cody
Upvotes: 3
Views: 1738
Reputation: 9260
As I said in my comment. Iterate over the outline path, get the winding and identify a segment starting point. When you hit the PathIterator.SEG_MOVETO
construct a java.awt.Path2D.Float
and add the points to it until you hit PathIterator.SEG_CLOSE
.
Here is an example I did for you to demonstrate
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();
}
}
Upvotes: 5