【问题标题】:Incorrect result of area when using java.awt.geom.Area with Rectangle2D将 java.awt.geom.Area 与 Rectangle2D 一起使用时的区域结果不正确
【发布时间】:2012-08-06 21:30:54
【问题描述】:

我最近使用 Java Area 类来包装一个 Rectangle2D.Double 类型。这样我就可以进行相交、相加等操作。但是,在计算形状面积时,我得到了一个非常奇怪的结果。下面是我用来计算形状面积的代码:

private static double polyArea(ArrayList<Point2D.Double> pointList) {
    double area = 0;
    for (int loopi = 1; loopi < pointList.size(); loopi++) {
        Point2D.Double p1 = pointList.get(loopi - 1);
        Point2D.Double p2 = pointList.get(loopi);
        area += (p1.x * p2.y - p2.x * p1.y) / 2.0;
    }
    return area;
}

public  static double coverageArea(Shape s) {
    ArrayList<Point2D.Double> pointList = new ArrayList<Point2D.Double>();
    double[] coords = new double[6];
    int type;
    double totalArea = 0;
    PathIterator it = s.getPathIterator(null);
    while (!it.isDone()) {
        type = it.currentSegment(coords);
        if (type == it.SEG_MOVETO) {
            pointList.clear();
            pointList.add(new Point2D.Double(coords[0], coords[1]));
        } else if (type == it.SEG_LINETO) {
            pointList.add(new Point2D.Double(coords[0], coords[1]));
        } else if (type == it.SEG_CLOSE) {
            totalArea += polyArea(pointList);
            pointList.clear();
        } else {
            System.out.println("calculateShapeArea: Cannot calculate area for shapes with segment type other than SEG_MOVETO, SEG_LINETO, or SEG_CLOSE.  Ignoring segment type=" + type);
        }
        it.next();
    }
    if (totalArea < 0) {
        totalArea = -totalArea;
    }
    return totalArea;
}

如果我有一个Rectangle2D r(1.0, 1.0, 6.0, 6.0),使用上面的代码我会正确地得到面积36。但是如果我做a = new Area(r),那么coverageArea(a)的结果是39 . 有时它可能比正确答案大几十倍。

有人知道为什么会这样吗?面积计算有问题吗?任何建议将不胜感激!

【问题讨论】:

    标签: java area


    【解决方案1】:

    根据Wiki,您的代码未正确实现该方法。您的 polyArea() 方法忘记 close 多边形(它不考虑从 lastfirst 顶点的线)。

    另外,你的公式版本似乎交换了 p1 和 p2,虽然我不确定这是否有问题,但我个人不明白 这个方法是如何真正起作用的。

    【讨论】:

    • 我认为您确实一针见血,结果总是不正确的原因正如您所提到的,PolyArea() 方法不会关闭多边形。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    相关资源
    最近更新 更多