public static Nullable<Point> GetNearestPointOfIntersectionBetweenRectAndSegment( Rect rect, Segment segment, Point point ) { Nullable<Point> result = null; double distance = double.PositiveInfinity; Segment leftIntersection = segment.Intersection( new Segment( rect.BottomLeft, rect.TopLeft ) ); Segment topIntersection = segment.Intersection( new Segment( rect.TopLeft, rect.TopRight ) ); Segment rightIntersection = segment.Intersection( new Segment( rect.TopRight, rect.BottomRight ) ); Segment bottomIntersection = segment.Intersection( new Segment( rect.BottomRight, rect.BottomLeft ) ); RectHelper.AdjustResultForIntersectionWithSide( ref result, ref distance, leftIntersection, point ); RectHelper.AdjustResultForIntersectionWithSide( ref result, ref distance, topIntersection, point ); RectHelper.AdjustResultForIntersectionWithSide( ref result, ref distance, rightIntersection, point ); RectHelper.AdjustResultForIntersectionWithSide( ref result, ref distance, bottomIntersection, point ); return result; }