我接受了AlmastB的建議,並決定創建我自己的Line2D
類,以便與javafx.geometry.Point2D
類兼容。
public class Line2D {
double x1;
double y1;
double x2;
double y2;
public Line2D(double x1, double y1, double x2, double y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public Line2D(Point2D point1, Point2D point2) {
this(point1.getX(), point1.getY(), point2.getX(), point2.getY());
}
public double length()
{
return new Point2D(x1, y1).distance(x2, y2);
}
public double distance(double x, double y) {
double d1 = x * (y2 - y1) - y * (x2 - x1) + x2 * y1 - y2 * x1;
return Math.abs(d1)/length();
}
public double distance(Point2D toPoint) {
return distance(toPoint.getX(), toPoint.getY());
}
}
正如你會發現,原本我僅做了一個distance
方法。一個intersects
方法是棘手的,因爲它需要比較double
值。使用浮點數進行操作可能會引入小偏差。總之:你只能判斷一個點是否在一條線上,以一定的精度。很難說什麼精度應該是。
distance
方法也有一個關注點。它假設這條線貫穿2點,但不受它限制(即它有一個無限長度)。
相交方法
一種intersects
方法將如下所示:
public boolean intersects(Point2D toPoint, double precision, boolean checkBounds) {
if (checkBounds &&
((toPoint.getX() < Math.min(x1, x2) - precision) ||
(toPoint.getX() > Math.max(x1, x2) + precision) ||
(toPoint.getY() < Math.min(y1, y2) - precision) ||
(toPoint.getY() > Math.max(y1, y2) + precision))) return false;
return distance(toPoint.getX(), toPoint.getY()) < precision;
}
這需要在帳戶中的2個先前講話(即精度和範圍)。
所以請使用'rt.jar' – SaviNuclear
每當有現代化的選擇時,我們是否應該避免使用'awt'類(即Java 1.2)? – bvdb