有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中获取Path2D对象的坐标对?

我必须获得Path2D对象中每一组坐标的坐标,但我不知道如何获得。之前我们使用多边形,所以我能够初始化两个长度为Polygon.npoints的数组,然后将它们设置为Polygon.xpointsPolygon.ypoints数组。现在我们使用的是Path2D对象,我不知道该怎么做,因为我所能做的就是初始化PathIterator,它将数组作为输入并返回段?有人能解释一下如何获取Path2D对象的所有坐标对吗


共 (1) 个答案

  1. # 1 楼答案

    下面是一个例子,你可以得到一个物体的所有线段和坐标对 ^{}

    反复调用PathIterator^{}方法。 每次通话你都会得到一段的坐标。 请特别注意,坐标数取决于线段类型 (从currentSegment方法得到的返回值)

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

    您可以使用此方法转储任何^{} (因此也适用于它的实现,比如RectanglePolygonEllipse2DPath2D,…)

    Shape shape = ...;
    dump(shape);