• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#判断两条直线是否相交

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

直接上代码,过程不复杂

/// <summary>
/// 判断两条线是否相交
/// </summary>
/// <param name="a">线段1起点坐标</param>
/// <param name="b">线段1终点坐标</param>
/// <param name="c">线段2起点坐标</param>
/// <param name="d">线段2终点坐标</param>
/// <param name="intersection">相交点坐标</param>
/// <returns>是否相交 0:两线平行  -1:不平行且未相交  1:两线相交</returns>

private int GetIntersection(Point a, Point b, Point c, Point d ,ref Point intersection)
{
    //判断异常
    if (Math.Abs(b.X - 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 == 0)
        {
           Debug.Print("ABCD是同一个点!"); 
        }
        else
        {
            Debug.Print("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)
        {
            Debug.Print ("A、B是一个点,且在CD线段上!");
        }
        else
        {
             Debug.Print ("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)
        {
            Debug.Print ("C、D是一个点,且在AB线段上!");
        }
        else
        {
            Debug.Print ("C、D是一个点,且不在AB线段上!");
        }
    }


    if ((b.Y - a.Y) * (c.X - d.X) - (b.X - a.X) * (c.Y - d.Y) == 0)
    {
        Debug.Print ("线段平行,无交点!");
        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) <= 0 && (intersection.X - c.X) * (intersection.X - d.X) <= 0 && (intersection.Y - a.Y) * (intersection.Y - b.Y) <= 0 && (intersection.Y - c.Y) * (intersection.Y - d.Y) <= 0)
    {
        Debug.Print ("线段相交于点(" + intersection.X + "," + intersection.Y + ")!");
        return 1; //'相交
    }
    else
    {
        Debug.Print ("线段相交于虚交点(" + intersection.X + "," + intersection.Y + ")!");
        return -1; //'相交但不在线段上
    }
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#Chart折线图多条数据展示发布时间:2022-07-14
下一篇:
在C#中压缩解压缩文件(适合.Net1.x)发布时间:2022-07-14
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap