BLOG.CSHARPHELPER.COM: Find the shortest distance between two line segments in C#
Find the shortest distance between two line segments in C#
Click four points to pick the end points for the two segments. The program finds the closest points on the two segments and connects them. The FindDistanceBetweenSegments method returns the smallest distance between the segments and returns the closest points on the segments through output parameters.
The closest distance between two segments is either zero if they intersect or the distance from one of the lines' end points to the other line. FindDistanceBetweenSegments first calls the FindIntersection method to see if the segments intersect. If they do, FindDistanceBetweenSegments returns zero and returns the point of intersection for both of the closest points.
If the segments do not intersect, the method calculates the shortest distance from the first segment's end points to the second segment and vice versa. It then returns the shortest distance.
The following code shows the FindDistanceBetweenSegments method.
// Return the shortest distance between the two segments // p1 --> p2 and p3 --> p4. private double FindDistanceBetweenSegments(PointF p1, PointF p2, PointF p3, PointF p4, out PointF close1, out PointF close2) { // See if the segments intersect. bool lines_intersect, segments_intersect; PointF intersection; FindIntersection(p1, p2, p3, p4, out lines_intersect, out segments_intersect, out intersection, out close1, out close2); if (segments_intersect) { // They intersect. close1 = intersection; close2 = intersection; return 0; }
// Find the other possible distances. PointF closest; double best_dist = double.MaxValue, test_dist;
Comments