简体   繁体   中英

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

I was recently using the Java Area class to wrap up a Rectangle2D.Double type. So that I can do manipulations like intersect, add, etc. However, when it comes to the calculation of the area of the shape, I was getting a quite weird result. Below is the code I'm using to calculate the area of a shape:

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

If I have a Rectangle2D r(1.0, 1.0, 6.0, 6.0), using the above code I will get the area correctly 36. However if I do a = new Area(r) , then the result of coverageArea(a) is 39. Sometimes it could be tens of times larger than the correct answer.

Anyone knows why this is happening? Is there any problem with the area calculation? Any advice would be appreciated!

According to this Wiki , your code is not implementing the method correctly. Your polyArea() method forget to close the polygon (it does not consider the line from the last to the first vertex).

Also your version of the formula seems to have exchanged p1 and p2, although I'm not sure if thats a problem, I don't personally understand how this method really works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM