I have to get the coordinates of each set of coordinates in a Path2D object but I don't know how. Previously we were using Polygons, so I was able to initialize two arrays of length Polygon.npoints
and then set them to be the Polygon.xpoints
and Polygon.ypoints
arrays. Now that we are using Path2D objects, I have no idea how to do this, because all I can seem to do is initialize a PathIterator, which takes an array as input and returns segments? Can somebody explain how to get all the coordinate pairs of a Path2D object?
Asked
Active
Viewed 1,122 times
0

Thomas Fritsch
- 9,639
- 33
- 37
- 49

wfgeo
- 2,716
- 4
- 30
- 51
1 Answers
2
Below is an example how you can get all the segments and coordinate pairs of a
PathIterator
:
You call the PathIterator
's currentSegment
method repeatedly.
On each call you get the coordinates of one segment.
Note especially that the number of coordinates depends on the segment type
(the return value you got from the currentSegment
method).
public static void dump(Shape shape) {
float[] coords = new float[6];
PathIterator pathIterator = shape.getPathIterator(new AffineTransform());
while (!pathIterator.isDone()) {
switch (pathIterator.currentSegment(coords)) {
case PathIterator.SEG_MOVETO:
System.out.printf("move to x1=%f, y1=%f\n",
coords[0], coords[1]);
break;
case PathIterator.SEG_LINETO:
System.out.printf("line to x1=%f, y1=%f\n",
coords[0], coords[1]);
break;
case PathIterator.SEG_QUADTO:
System.out.printf("quad to x1=%f, y1=%f, x2=%f, y2=%f\n",
coords[0], coords[1], coords[2], coords[3]);
break;
case PathIterator.SEG_CUBICTO:
System.out.printf("cubic to x1=%f, y1=%f, x2=%f, y2=%f, x3=%f, y3=%f\n",
coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]);
break;
case PathIterator.SEG_CLOSE:
System.out.printf("close\n");
break;
}
pathIterator.next();
}
}
You can use this method for dumping any Shape
(and hence also for its implementations like Rectangle
, Polygon
, Ellipse2D
, Path2D
, ...)
Shape shape = ...;
dump(shape);

Thomas Fritsch
- 9,639
- 33
- 37
- 49