Java 使用PathIterator返回约束区域的所有线段?

Java 使用PathIterator返回约束区域的所有线段?,java,2d,area,line-segment,path-iterator,Java,2d,Area,Line Segment,Path Iterator,在Java中,如何迭代约束对象的线段?区域仅由直线绑定(但曲线支撑不会造成伤害) 该方法应返回所有线段的集合。这是可行的(我相信在所有情况下),但可能需要更彻底的测试: Area area; // The value is set elsewhere in the code ArrayList<double[]> areaPoints = new ArrayList<double[]>(); ArrayList<Line2D.Double> areaS

在Java中,如何迭代约束对象的线段?
区域
仅由直线绑定(但曲线支撑不会造成伤害)

该方法应返回所有线段的集合。

这是可行的(我相信在所有情况下),但可能需要更彻底的测试:

Area area; // The value is set elsewhere in the code    
ArrayList<double[]> areaPoints = new ArrayList<double[]>();
ArrayList<Line2D.Double> areaSegments = new ArrayList<Line2D.Double>();
double[] coords = new double[6];

for (PathIterator pi = area.getPathIterator(null); !pi.isDone(); pi.next()) {
    // The type will be SEG_LINETO, SEG_MOVETO, or SEG_CLOSE
    // Because the Area is composed of straight lines
    int type = pi.currentSegment(coords);
    // We record a double array of {segment type, x coord, y coord}
    double[] pathIteratorCoords = {type, coords[0], coords[1]};
    areaPoints.add(pathIteratorCoords);
}

double[] start = new double[3]; // To record where each polygon starts

for (int i = 0; i < areaPoints.size(); i++) {
    // If we're not on the last point, return a line from this point to the next
    double[] currentElement = areaPoints.get(i);

    // We need a default value in case we've reached the end of the ArrayList
    double[] nextElement = {-1, -1, -1};
    if (i < areaPoints.size() - 1) {
        nextElement = areaPoints.get(i + 1);
    }

    // Make the lines
    if (currentElement[0] == PathIterator.SEG_MOVETO) {
        start = currentElement; // Record where the polygon started to close it later
    } 

    if (nextElement[0] == PathIterator.SEG_LINETO) {
        areaSegments.add(
                new Line2D.Double(
                    currentElement[1], currentElement[2],
                    nextElement[1], nextElement[2]
                )
            );
    } else if (nextElement[0] == PathIterator.SEG_CLOSE) {
        areaSegments.add(
                new Line2D.Double(
                    currentElement[1], currentElement[2],
                    start[1], start[2]
                )
            );
    }
}

// areaSegments now contains all the line segments
面积;//该值在代码的其他位置设置
ArrayList areaPoints=新建ArrayList();
ArrayList areaSegments=新建ArrayList();
双[]坐标=新双[6];
for(PathIterator pi=area.getPathIterator(null);!pi.isDone();pi.next()){
//类型将为SEG_LINETO、SEG_MOVETO或SEG_CLOSE
//因为这个区域是由直线组成的
int type=pi.currentSegment(坐标);
//我们记录了一个{段类型,x坐标,y坐标}的双数组
double[]pathIteratorCoords={type,coords[0],coords[1]};
areaPoints.add(路径迭代器或文件夹);
}
双精度[]开始=新双精度[3];//记录每个多边形的起始位置的步骤
对于(int i=0;i
感谢您成为SO中的少数成员之一,以便在您的代码中包含注释!这对于查找路径的各个点也非常有帮助(可以通过循环遍历线段并抓住第一个点,或者通过跳过线段生成来简化算法)。您可以将路径迭代器包装在中,以将曲线转换为直线,然后使用上述解决方案