最近使用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;
}