【发布时间】:2012-08-21 01:22:59
【问题描述】:
给定由 (x1, y1) 和 (x2, y2) 定义的线段,求直线上 y = 某个值的位置。
我知道我可以获得直线方程,然后使用联立方程求解,但这是否可以使用 Line2D 或任何其他 Java 类?
任何建议或 cmets 将不胜感激!
开尔文。
【问题讨论】:
标签: java 2d line coordinate
给定由 (x1, y1) 和 (x2, y2) 定义的线段,求直线上 y = 某个值的位置。
我知道我可以获得直线方程,然后使用联立方程求解,但这是否可以使用 Line2D 或任何其他 Java 类?
任何建议或 cmets 将不胜感激!
开尔文。
【问题讨论】:
标签: java 2d line coordinate
我认为 Java API 中没有任何东西可以实际计算交集。我认为最接近的方法是使用 Line2D 来测试线段是否与(垂直)线 y = k 相交以获得一些常数 k:
Line2D line = new Line2D.Double(x1, y1, x2, y2);
if (line.intersectsLine(Double.MIN_VALUE, k, Double.MAX_VALUE, k)) {
double x = (x2 - x1) * (k - y1) / (y2 - y1);
// intersection is at (x, k)
} else {
// intersection is outside extend of the line segment
}
但是,只检查y1 != y2,计算交点,然后检查 x 坐标是否在 [x1, x2] 范围内可能会更有效。
【讨论】:
对于这样的任务,我建议使用 apache commons math。
http://commons.apache.org/math/apidocs/index.html
有多种方法可以做到这一点。一种方法是
org.apache.commons.math3.geometry.euclidean.twod.Line lineOne = new org.apache.commons.math3.geometry.euclidean.twod.Line(p,angle);
org.apache.commons.math3.geometry.euclidean.twod.Line horizontalLine = new org.apache.commons.math3.geometry.euclidean.twod.Line(new vector2d(0,yToSolveFor),pi/2);
Vector2D intersection=lineOne.intersect(horizontalLine);
intersection.getX(); // The answer
【讨论】: