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).
Advertisement
Answer
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:
JavaScript
x
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()
.