C# 判斷兩條直線是否相交

來源:互聯網
上載者:User

標籤:

直接上代碼,過程不複雜

/// <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; //‘相交但不線上段上    }}

C# 判斷兩條直線是否相交

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.