最近、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 になります。正しい値よりも数十倍大きくなる場合があります。答え。
なぜこれが起こっているのか誰にも分かりますか?面積計算に問題はありますか?アドバイスをいただければ幸いです。