今晚參考了http://www.BkJia.com/kf/201111/112304.html
寫了判斷兩線段是否相交的c#代碼。基本思想是相交的兩條線段,對於任意一線段的兩端點,都在另一條直線的兩邊。
/// <summary>
/// 判斷直線2的兩點是否在直線1的兩邊。
/// </summary>
/// <param name="line1">直線1</param>
/// <param name="line2">直線2</param>
/// <returns></returns>
private bool CheckCrose(Line line1, Line line2)
{
PointF v1 = new PointF();
PointF v2 = new PointF();
PointF v3 = new PointF();
v1.X = line2.Start.X - line1.End.X;
v1.Y = line2.Start.Y - line1.End.Y;
v2.X = line2.End.X - line1.End.X;
v2.Y = line2.End.Y - line1.End.Y;
v3.X = line1.Start.X - line1.End.X;
v3.Y = line1.Start.Y - line1.End.Y;
return (CrossMul(v1, v3) * CrossMul(v2, v3) <= 0);
}
/// <summary>
/// 判斷兩條線段是否相交。
/// </summary>
/// <param name="line1">線段1</param>
/// <param name="line2">線段2</param>
/// <returns>相交返回真,否則返回假。</returns>
private bool CheckTwoLineCrose(Line line1, Line line2)
{
return CheckCrose(line1, line2) && CheckCrose(line2, line1);
}
/// <summary>
/// 計算兩個向量的叉乘。
/// </summary>
/// <param name="pt1"></param>
/// <param name="pt2"></param>
/// <returns></returns>
private float CrossMul(PointF pt1, PointF pt2)
{
return pt1.X * pt2.Y - pt1.Y * pt2.X;
}
作者 I_code