计算两条线是否相交

计算两条线段是否相交 并返回相交的位置

0x01 调用方式

			Point s1 = new Point(50, 50);
            Point e1 = new Point(50, 250);
            Point s2 = new Point(-20, 85);
            Point e2 = new Point(650, 85);

            var pp = GetIntersection(s1, e1, s2, e2);
            if (pp.HasValue)
            {
                Console.WriteLine(pp);
            }

0x02 源码

        /// 
        /// 判断两条线是否相交
        /// 
        /// 线段1起点坐标
        /// 线段1终点坐标
        /// 线段2起点坐标
        /// 线段2终点坐标
        /// 相交点坐标
        private static Nullable<Point> GetIntersection(Point a, Point b, Point c, Point d)
        {
            Point intersection = new Point(0, 0);
            //判断异常
            if (Math.Abs(b.X - a.Y) + Math.Abs(b.X - a.X) + Math.Abs(d.Y - c.Y) + Math.Abs(d.X - c.X) == 0)
            {
                return null;
            }
            if (Math.Abs(b.Y - a.Y) + Math.Abs(b.X - a.X) == 0)
            {
                return null;
            }
            if ((b.Y - a.Y) * (c.X - d.X) - (b.X - a.X) * (c.Y - d.Y) == 0)
            {
                return null;
            }
            intersection.X = ((b.X - a.X) * (c.X - d.X) * (c.Y - a.Y) - c.X * (b.X - a.X) * (c.Y - d.Y) + a.X * (b.Y - a.Y) * (c.X - d.X)) / ((b.Y - a.Y) * (c.X - d.X) - (b.X - a.X) * (c.Y - d.Y));
            intersection.Y = ((b.Y - a.Y) * (c.Y - d.Y) * (c.X - a.X) - c.Y * (b.Y - a.Y) * (c.X - d.X) + a.Y * (b.X - a.X) * (c.Y - d.Y)) / ((b.X - a.X) * (c.Y - d.Y) - (b.Y - a.Y) * (c.X - d.X));
            if ((intersection.X - a.X) * (intersection.X - b.X) <= 0 && (intersection.X - c.X) * (intersection.X - d.X) <= 0 && (intersection.Y - a.Y) * (intersection.Y - b.Y) <= 0 && (intersection.Y - c.Y) * (intersection.Y - d.Y) <= 0)
            {
                //'相交
                return intersection;
            }
            else
            {
                //'相交但不在线段上
                return null;
            }
        }

你可能感兴趣的:(C#,几何,线段相交)