简体   繁体   English

java.awt.geom.Area减法后返回多个部分?

[英]java.awt.geom.Area return multiple parts after subtraction?

I want to use Java's Area class (java.awt.geom.Area) to preform subtraction and intersection operations on various polygons. 我想使用Java的Area类(java.awt.geom.Area)在各种多边形上执行减法和交集操作。

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. 在这些情况下,我需要返回两个Area对象,每个对象用于由减法操作创建的每个结果连续部分。

After reading through the JavaDocs on the Area class I haven't seemingly found any way to return a contiguous part of the Area. 在阅读了Area类的JavaDocs之后,我似乎没有找到任何方法来返回Area的连续部分。 In fact I'm not even sure how Area handles such a situation. 事实上,我甚至不确定Area如何处理这种情况。

How would I get all of the resulting contiguous Area's created by Area's subtraction or intersection methods? 如何通过Area的减法或交叉方法获得所有生成的连续区域?

Thanks, -Cody 谢谢,-Cody

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 . 当您点击PathIterator.SEG_MOVETO构造一个java.awt.Path2D.Float并向其添加点,直到您点击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();
    }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM