码迷,mamicode.com
首页 > 其他好文 > 详细

求两条直线的交点

时间:2015-04-08 12:55:14      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

        /// <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;
        }

 

求两条直线的交点

标签:

原文地址:http://www.cnblogs.com/moisten/p/4401840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!