在 Java 中获取 Path2D 对象的坐标对?
Getting the coordinate pairs of a Path2D object in Java?
我必须获取 Path2D 对象中每组坐标的坐标,但我不知道如何获取。之前我们使用的是多边形,所以我能够初始化两个长度为 Polygon.npoints
的数组,然后将它们设置为 Polygon.xpoints
和 Polygon.ypoints
数组。现在我们正在使用 Path2D 对象,我不知道该怎么做,因为我似乎只能初始化一个 PathIterator,它将数组作为输入和 returns 段?有人可以解释一下如何获取 Path2D 对象的所有坐标对吗?
下面是一个例子,你如何得到一个的所有线段和坐标对
PathIterator
:
您重复调用 PathIterator
的 currentSegment
方法。
在每次调用中,您都会获得一段的坐标。
特别注意坐标的数量取决于线段类型
(您从 currentSegment
方法获得的 return 值)。
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();
}
}
您可以使用此方法转储任何 Shape
(因此也用于它的实现,如 Rectangle
、Polygon
、Ellipse2D
、Path2D
、...)
Shape shape = ...;
dump(shape);
我必须获取 Path2D 对象中每组坐标的坐标,但我不知道如何获取。之前我们使用的是多边形,所以我能够初始化两个长度为 Polygon.npoints
的数组,然后将它们设置为 Polygon.xpoints
和 Polygon.ypoints
数组。现在我们正在使用 Path2D 对象,我不知道该怎么做,因为我似乎只能初始化一个 PathIterator,它将数组作为输入和 returns 段?有人可以解释一下如何获取 Path2D 对象的所有坐标对吗?
下面是一个例子,你如何得到一个的所有线段和坐标对
PathIterator
:
您重复调用 PathIterator
的 currentSegment
方法。
在每次调用中,您都会获得一段的坐标。
特别注意坐标的数量取决于线段类型
(您从 currentSegment
方法获得的 return 值)。
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();
}
}
您可以使用此方法转储任何 Shape
(因此也用于它的实现,如 Rectangle
、Polygon
、Ellipse2D
、Path2D
、...)
Shape shape = ...;
dump(shape);