已知两点和直线上的某点的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;

        }

你可能感兴趣的:(GDI绘图)