簡體   English   中英

將Rectangle2D與java.awt.geom.Area一起使用時,區域的結果不正確

[英]Incorrect result of area when using java.awt.geom.Area with Rectangle2D

我最近正在使用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有時它可能比正確答案大幾十倍。

有人知道為什么會這樣嗎? 面積計算有問題嗎? 任何意見,將不勝感激!

根據此Wiki ,您的代碼未正確實現該方法。 您的polyArea()方法忘記關閉多邊形(它不考慮從最后 一個頂點到第一個頂點的線)。

此外,您的公式的版本似乎有交換p1和p2,雖然我不知道如果多數民眾贊成的問題,我不親自了解這種方法確實有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM