已知兩點和直線上的某點的Y值,求某點的x座標

最近使用GDI繪圖,繪製了不規則曲線和一條直線,需要填充直線和曲線的相交區域,這就需要計算它們的交點了。以下是應用數學幾何代數上的知識,通過已知的兩點獲得直線公式,然後根據直線上某點的Y值,獲得某點的x值,具體的代碼如下:

  //已知兩點和直線上的某點的Y值,求某點的x座標
        private Point GetInsectPoint(Point pt1, Point pt2, int insectPtY)
        {
            Point pt = new Point();
            try
            {
                float k = 0f;
                if (pt1.X == pt2.X)//不存在斜率x=x1爲直線方程90度
                {
                    pt.X = pt1.X;
                    pt.Y = insectPtY;
                    return pt;
                }
                else if (pt1.Y == pt2.Y && pt1.Y != insectPtY)//y=y1爲直線方程,0度,兩條直線平行沒有交點
                {
                    return pt;
                }
                else if (pt1.Y == pt2.Y && pt1.Y == insectPtY)//0度,兩條直線重合,任意點即爲交點
                {
                    pt.X = pt1.X;
                    pt.Y = insectPtY;
                    return pt;
                }
                else
                {
                    k = (float)(pt2.Y - pt1.Y) /(float) (pt2.X - pt1.X);
                    float b = pt1.Y - k * pt1.X;                   

                    float x = (insectPtY - b) / k;
                    pt.X = (int)x;
                    pt.Y = insectPtY;
                }

            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex, "通過兩點計算直線公式失敗:" + ex.Message);
            }
            return pt;

        }

發佈了66 篇原創文章 · 獲贊 5 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章