标准线方程 Ax+By=C
由标准方程线定义的直线的斜率(m)为
m = -(A/B)
点斜线方程y-y1=m(x-x1)
将 m = (-A/B) 代入点斜线方程 y2-y1 = (A/-B)*(x2-x1)
(y2-y1)/(x2-x1) = A/-B
因此:
A = y2-y1
B = x1-x2 C = Ax+By
x = (C-By)/A
y = (C-Ax)/B
给定两行方程 A1x1+B1y1=C1 和 A2x2+B2y2=C2。
然后线之间的交点由使
A1x+B1y-C1 = A2x+B2y-C2的点指定
A1x+B1y=C1
A2x+B2y=C2
A1B2x+B1B2y=B2C1(将第一个方程乘以B2)
A1B2x+B1B2y-B2C1=0
A2B1x+B1B2y=B1C2(第二个等式乘以B1)
A2B1x+B1B2y-B1C2=0
等式
A1B2x+B1B2y-B2C1=A2B1x+B1B2y-B1C2
A1B2x+B1B2y-B2C1-A2B1x-B1B2y+B1C2=0
A1B2x-B2C1-A2B1x+B1C2=0
A1B2x-A2B1x=B2C1-B1C2
x(A1B2-A) =B2C1-B1C2
x = (B2C1-B1C2)/A1B2-A2B1
A1x+B1y=C1
A2x+B2y=C2
A1A2x+A2B1y=A2C1(将第一个方程乘以A2)
A1A2x+A2B1y-A2C1=0
A1A2x+A1B2y=A1C2(第二个等式乘以A1)
A1A2x+A1B2y-A1C2=0
使两个方程相等
A1A2x+A2B1y-A2C1=A1A2x+A1B2y-A1C2
A1A2x+A2B1y-A2C1-A1A2x-A1B2y+A1C2=0
A1C2-A2C2=A1B2y-A2B1y
A1B2y-A2B1y=A1C2-A2C2
y(A1B2-A2B1)(A1B2-A2B1)=
A1C A1B2-A2B1)=A1C2-A2C1
y = (A1C2-A2C1)/(A1B1-A2B1)
y 和 x 中的分母相同,因此分母 = A1B1-A2B1
因此:
x = (B2C1-B1C2)/分母
y = (A1C2-A2C1)/分母
这些是两条线与点 (x1, y1)、(x2, y2)和 (x3, y3)、(x4, y4)相交的 x 和 y 坐标
现在对于一条线段,它是相同的,但我们需要检查 x 或 y 坐标是否在两个线段中。这意味着在具有较小值的两个段的 x 坐标和具有较大值的两个段的 x 坐标之间
这是一个 C++ 程序,如果段相交则返回 true,否则返回 false。如果线段相交,它将交点存储在变量 i 中。
struct Point
{
float x, y;
};
//p1 and p2 are the points of the first segment
//p3 and p4 are the points of the second segment
bool intersection(Point p1, Point p2, Point p3, Point p4, Point &i)
{
float max1; //x-coordinate with greater value in segment 1
float min1; //x-coordinate with lesse value in segment 1
float max2; //x-coordinate with greater value in segment 2
float min2; //x-coordinate with lesser value in segment 2
float A1 = p2.y - p1.y;
float B1 = p1.x - p2.x;
float C1 = A1 * p1.x + B1 * p1.y;
float A2 = p4.y - p3.y;
float B2 = p3.x - p4.x;
float C2 = A2 * p3.x + B2 * p3.y;
float denom = A1 * B2 - A2 * B1;
if (denom == 0.0) //When denom == 0, is because the lines are parallel
return false; //Parallel lines do not intersect
i.x = (C1 * B2 - C2 * B1) / denom;
i.y = (A1 * C2 - A2 * C1) / denom;
if (p1.x > p2.x)
{
max1 = p1.x;
min1 = p2.x;
}
else
{
max1 = p2.x;
min1 = p1.x;
}
if (p3.x > p4.x)
{
max2 = p3.x;
min2 = p4.x;
}
else
{
max2 = p4.x;
min2 = p3.x;
}
//check if x coordinate is in both segments
if (i.x >= min1 && i.x <= max1 &&
i.x >= min2 && i.x <= max2)
return true;
return false; //Do no intersect, intersection of the lines is not between the segments
}
现在您只需要在循环上比较所有段并将交点存储在数组中。