3

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

Cody Smith
  • 2,732
  • 3
  • 31
  • 43
  • What I'm talking about is taking two closed Area objects, running subtract on them (say A subtract B) and the result being an Area which is split down the center. From what I understand that result is returned as a single Area object. So how could I distil it's parts? – Cody Smith Sep 14 '12 at 09:22
  • Did my answer helped you in any way? – nullpotent Sep 14 '12 at 15:59
  • A recently deleted question prompts me to cite this [example](http://stackoverflow.com/a/4530659/230513). – trashgod Sep 22 '12 at 21:23

1 Answers1

5

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();
    }
   }
nullpotent
  • 9,162
  • 1
  • 31
  • 42