你的位置:首页 > ASP.net教程

[ASP.net教程]求两条直线的交点


    /// <summary>    /// 求两条线的交点    /// </summary>    /// <param name="point">前两个点与后两个点分别确定两条直线</param>    /// <returns>两直线焦点</returns>    private Point GetIntersectionyOfTwoLines(Point[] point)    {      Point intersectiony = new Point();      if (point.Length != 4)        throw new AggregateException("参数个数不正确");      if (point[0].Equals(point[1]) && point[2].Equals(point[4]))        throw new ArgumentException("参数相同");      bool line1IsVertical, line2IsVertical;      line1IsVertical = point[1].X.Equals(point[0].X);      line2IsVertical = point[3].X.Equals(point[2].X);      if (line1IsVertical || line2IsVertical) //两条直线存在垂直的情况      {        if (line1IsVertical && line2IsVertical)        {          throw new ArgumentException("两直线平行,无交点");        }        else        {          if (line1IsVertical)          {            intersectiony.X = point[0].X;            double differenceX = point[3].X - point[2].X;            double differenceY = point[3].Y - point[2].Y;            intersectiony.Y = differenceY * (intersectiony.X - point[2].X) / differenceX + point[2].Y;          }          else          {            intersectiony.X = point[2].X;            double differenceX = point[1].X - point[0].X;            double differenceY = point[1].Y - point[0].Y;            intersectiony.Y = differenceY * (intersectiony.X - point[0].X) / differenceX + point[0].Y;          }        }      }      else      {        double differenceX1 = point[1].X - point[0].X;        double differenceX2 = point[3].X - point[2].X;        double differenceY1 = point[1].Y - point[0].Y;        double differenceY2 = point[3].Y - point[2].Y;        if ((differenceY1 * differenceX2).Equals(differenceY2 * differenceX1))        {          throw new ArgumentException("两直线平行,无交点");        }        else        {          intersectiony.X = (point[0].Y - point[2].Y + differenceY2 * point[2].X / differenceX2 - differenceY1 * point[0].X / differenceX1) /                   (differenceY2 / differenceX2 - differenceY1 / differenceX1);          intersectiony.Y = differenceY1 * (intersectiony.X - point[0].X) / differenceX1 + point[0].Y;        }      }      return intersectiony;    }