如何获得GeneralPath对象的顶点?由于路径是由点(lineTo,curveTo等)构成的,因此这似乎应该可行。

我正在尝试创建一个double [] []点数据(x / y坐标数组)。

最佳答案

您可以从PathIterator返回点。

我不确定您的约束是什么,但是如果您的形状始终只有一个闭合的子路径,并且只有直边(没有曲线),那么以下方法将起作用:

static double[][] getPoints(Path2D path) {
    List<double[]> pointList = new ArrayList<double[]>();
    double[] coords = new double[6];
    int numSubPaths = 0;
    for (PathIterator pi = path.getPathIterator(null);
         ! pi.isDone();
         pi.next()) {
        switch (pi.currentSegment(coords)) {
        case PathIterator.SEG_MOVETO:
            pointList.add(Arrays.copyOf(coords, 2));
            ++ numSubPaths;
            break;
        case PathIterator.SEG_LINETO:
            pointList.add(Arrays.copyOf(coords, 2));
            break;
        case PathIterator.SEG_CLOSE:
            if (numSubPaths > 1) {
                throw new IllegalArgumentException("Path contains multiple subpaths");
            }
            return pointList.toArray(new double[pointList.size()][]);
        default:
            throw new IllegalArgumentException("Path contains curves");
        }
    }
    throw new IllegalArgumentException("Unclosed path");
}

如果路径中可能包含曲线,则可以使用the flattening version of getPathIterator()

09-30 17:52
查看更多