コード例 #1
0
        /// <summary>
        /// Get the <see cref="PdfPoint"/> that is the intersection of two lines.
        /// </summary>
        public static PdfPoint?Intersect(this PdfLine line, PdfLine other)
        {
            // if the bounding boxes do not intersect, the lines cannot intersect
            if (!line.GetBoundingRectangle().IntersectsWith(other.GetBoundingRectangle()))
            {
                return(null);
            }

            var eq1 = GetSlopeIntercept(line.Point1, line.Point2);
            var eq2 = GetSlopeIntercept(other.Point1, other.Point2);

            if (double.IsNaN(eq1.Slope) && double.IsNaN(eq2.Slope))
            {
                return(null);                                                    // both lines are vertical (hence parallel)
            }
            if (eq1.Slope == eq2.Slope)
            {
                return(null);                        // both lines are parallel
            }
            var intersection = new PdfPoint();

            if (double.IsNaN(eq1.Slope))
            {
                var x = eq1.Intercept;
                var y = eq2.Slope * x + eq2.Intercept;
                intersection = new PdfPoint(x, y);
            }
            else if (double.IsNaN(eq2.Slope))
            {
                var x = eq2.Intercept;
                var y = eq1.Slope * x + eq1.Intercept;
                intersection = new PdfPoint(x, y);
            }
            else
            {
                var x = (eq2.Intercept - eq1.Intercept) / (eq1.Slope - eq2.Slope);
                var y = eq1.Slope * x + eq1.Intercept;
                intersection = new PdfPoint(x, y);
            }

            // check if the intersection point belongs to both segments
            // (for the moment we only know it belongs to both lines)
            if (!line.Contains(intersection))
            {
                return(null);
            }
            if (!other.Contains(intersection))
            {
                return(null);
            }
            return(intersection);
        }