两条线段相交的交点计算
当两条线相交时会返回交点坐标,否则会返回null。
// 计算两线段交点
public static Point2f? GetIntersectionPoint(Point2f P1, Point2f P2, Point2f P3, Point2f P4)
{
float denom = (P4.X - P3.X) * (P2.Y - P1.Y) - (P2.X - P1.X) * (P4.Y - P3.Y);
if (denom == 0) return null;
float t1 = ((P3.X - P1.X) * (P3.Y - P4.Y) - (P3.Y - P1.Y) * (P3.X - P4.X)) / denom;
return new Point2f(P1.X + t1 * (P2.X - P1.X), P1.Y + t1 * (P2.Y - P1.Y));
}
例如:
当前给出两线坐标为
线1 (101.2, 150.2) (405.3, 100) 线2 (101.2,411.4)(400.01, 55.5)
将参数传入函数
Point2f? ptf = GetIntersectionPoint(new Point2f(101.2f, 150.2f), new Point2f(405.3f, 100.0f), new Point2f(101.2f, 411.4f), new Point2f(400.01f, 55.5f));
输出结果为
图