版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
版权
java专栏收录该内容
18 篇文章0 订阅
订阅专栏
A本身无限长,假设B也无限长,直接求得AB的交点坐标,然后再判断该坐标是否在定长线段B的内部就可以了啊
AB本身就是两条直线,知道两端点就可以知道其直线方程,B也是一样,两个方程联立,
得到一个坐标,再看该坐标是否在B的定义域内就可以啊
A的两点为(x1,y1),(x2,y2)
则A的直线方程为l1:y-y1=(y2-y1)(x-x1)/(x2-x1)
B的两点为(x3,y3),(x4,y4)
则B的直线方程为l2:y-y3=(y4-y3)(x-x3)/(x4-x3)
联立解出交点坐标为的横坐标为:
x=(k2x3-y3-k1x1+y1)/(k2-k1)
其中k1=(y2-y1)/(x2-x1)
k2=(y4-y3)/(x4-x3)
可以推导出来
x = ((x2 - x1) * (x3 - x4) * (y3 - y1) -
x3 * (x2 - x1) * (y3 - y4) + x1 * (y2 - y1) * (x3 - x4)) /
((y2 - y1) * (x3 - x4) - (x2 - x1) * (y3 - y4));
同理也可以推导出y的值:
y = ((y2 - y1) * (y3 - y4) * (x3 - x1) -
y3 * (y2 - y1) * (x3 - x4) + y1 * (x2 - x1) * (y3 - y4)) /
((y2 - y1) * (y3 - y4) - (y2 - y1) * (x3 - x4));
发现x和y的求解公式,结构相同,只要把x换成y下标不变,就是求解y值的公式,
原理部分来自 http://zhidao.baidu.com/question/191530048.html?push=ql
********************************************************************
下面附上java的实现,
前提是:a 线段1起点坐标
b 线段1终点坐标
c 线段2起点坐标
d 线段2终点坐标
import java.awt.Point;
public class AlgorithmUtil {
public static void main(String[] args) {
AlgorithmUtil.GetIntersection(new Point(1, 2), new Point(1, 2),
new Point(1, 2), new Point(1, 2));
AlgorithmUtil.GetIntersection(new Point(1, 2), new Point(1, 2),
new Point(1, 4), new Point(1, 4));
AlgorithmUtil.GetIntersection(new Point(100, 1), new Point(100, 100),
new Point(100, 101), new Point(100, 400));
AlgorithmUtil.GetIntersection(new Point(5, 5), new Point(100, 100),
new Point(100, 5), new Point(5, 100));
}
* 判断两条线是否相交 a 线段1起点坐标 b 线段1终点坐标 c 线段2起点坐标 d 线段2终点坐标 intersection 相交点坐标
* reutrn 是否相交: 0 : 两线平行 -1 : 不平行且未相交 1 : 两线相交
private static int GetIntersection(Point a, Point b, Point c, Point d) {
Point intersection = new Point(0, 0);
if (Math.abs(b.y - a.y) + Math.abs(b.x - a.x) + Math.abs(d.y - c.y)
+ Math.abs(d.x - c.x) == 0) {
if ((c.x - a.x) + (c.y - a.y) == 0) {
System.out.println("ABCD是同一个点!");
} else {
System.out.println("AB是一个点,CD是一个点,且AC不同!");
}
return 0;
}
if (Math.abs(b.y - a.y) + Math.abs(b.x - a.x) == 0) {
if ((a.x - d.x) * (c.y - d.y) - (a.y - d.y) * (c.x - d.x) == 0) {
System.out.println("A、B是一个点,且在CD线段上!");
} else {
System.out.println("A、B是一个点,且不在CD线段上!");
}
return 0;
}
if (Math.abs(d.y - c.y) + Math.abs(d.x - c.x) == 0) {
if ((d.x - b.x) * (a.y - b.y) - (d.y - b.y) * (a.x - b.x) == 0) {
System.out.println("C、D是一个点,且在AB线段上!");
} else {
System.out.println("C、D是一个点,且不在AB线段上!");
}
return 0;
}
if ((b.y - a.y) * (c.x - d.x) - (b.x - a.x) * (c.y - d.y) == 0) {
System.out.println("线段平行,无交点!");
return 0;
}
intersection.x = ((b.x - a.x) * (c.x - d.x) * (c.y - a.y) -
c.x * (b.x - a.x) * (c.y - d.y) + a.x * (b.y - a.y) * (c.x - d.x)) /
((b.y - a.y) * (c.x - d.x) - (b.x - a.x) * (c.y - d.y));
intersection.y = ((b.y - a.y) * (c.y - d.y) * (c.x - a.x) - c.y
* (b.y - a.y) * (c.x - d.x) + a.y * (b.x - a.x) * (c.y - d.y))
/ ((b.x - a.x) * (c.y - d.y) - (b.y - a.y) * (c.x - d.x));
if ((intersection.x - a.x) * (intersection.x - b.x)