开发者

Obtain ordered vertices of GeneralPath

开发者 https://www.devze.com 2023-03-01 13:26 出处:网络
How can I obtain the vertices of a GeneralPath object? It seems like this should be possible, since the path is constructed f开发者_JS百科rom points (lineTo, curveTo, etc).

How can I obtain the vertices of a GeneralPath object? It seems like this should be possible, since the path is constructed f开发者_JS百科rom points (lineTo, curveTo, etc).

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


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().


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.


As far as i looked for, i didn't find any answer to : " how to extract summit of an Area, or GeneralPath either".

I can extract a bunch of segments. even a triangle area return more than 3 segments with this method.

while (!i.isDone()) {
   float[] coords = new float[2];
   int segType = i.currentSegment(coords);
   if (segType != PathIterator.SEG_CLOSE) {
      list.add(coords);
   }
   i.next();
}

return list;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号