Obtain ordered vertices of GeneralPath

回眸只為那壹抹淺笑 提交于 2019-12-05 02:48:08

问题


How can I obtain the vertices of a GeneralPath object? It seems like this should be possible, since the path is constructed from points (lineTo, curveTo, etc).

I'm trying to create a double[][] of point data (an array of x/y coordinates).


回答1:


You can get the points back from the PathIterator.

I'm not sure what your constraints are, but if your shape always has just one closed subpath and has only straight edges (no curves) then the following will work:

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");
}

If your path may contain curves, you can use the flattening version of getPathIterator().




回答2:


I'd doubt if it is always possible, if at all... JavaDoc says:

"The GeneralPath class represents a geometric path constructed from straight lines, and quadratic and cubic (Bézier) curves."

So if it is a curve, the points it'd contain not necessarily are part of a curve.



来源:https://stackoverflow.com/questions/5803111/obtain-ordered-vertices-of-generalpath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!