我最近使用 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。有时它可能比正确的大几十倍回答。
任何人都知道为什么会这样?面积计算有问题吗?任何意见,将不胜感激!