【问题标题】:Using PathIterator to return all line segments that constrain an Area?使用 PathIterator 返回所有约束区域的线段?
【发布时间】:2011-12-29 23:00:03
【问题描述】:

在Java 中,如何使用PathIterator 来遍历约束Area 的线段? Area 仅受线约束(但曲线支撑不会受到伤害)。

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

【问题讨论】:

    标签: java 2d area line-segment path-iterator


    【解决方案1】:

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

    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
    

    【讨论】:

    • 感谢您成为 SO 中的少数人之一,将 cmets 包含在您的代码中!
    • 这对于查找路径的各个点也非常有帮助(通过循环遍历段并抓住第一个点,或者通过跳过段生成来简化算法)。
    • 您可以将路径迭代器包装在 docs.oracle.com/javase/7/docs/api/java/awt/geom/… 中以将曲线转换为直线,然后使用上面的解决方案
    猜你喜欢
    • 2011-05-29
    • 2013-08-19
    • 1970-01-01
    • 2014-08-23
    • 2018-11-18
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多