当前位置:编程学习 > C#/ASP.NET >>

判断两线段是否相交的C#代码

今晚参考了http://www.zzzyk.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

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,