Find the shortest distance between a point and a line segment in C#

This example treats the segment as parameterized vector where the parameter t varies from 0 to 1. It finds the value of t that minimizes the distance from the point to the line. If t is between 0.0 and 1.0, then the closest point lies on the segment, otherwise the closest point is one of the segment's end points. The program finds this closest point and calculates the distance between it and the target point.

The following code shows how the program finds the distance between the point pt and the segment p1 --> p2.

// Calculate the distance between
// point pt and the segment p1 --> p2.
private double FindDistanceToSegment(PointF pt, PointF p1, PointF p2, out PointF closest)
{
float dx = p2.X - p1.X;
float dy = p2.Y - p1.Y;
if ((dx == 0) && (dy == 0))
{
// It's a point not a line segment.
closest = p1;
dx = pt.X - p1.X;
dy = pt.Y - p1.Y;
return Math.Sqrt(dx * dx + dy * dy);
}

// Calculate the t that minimizes the distance.
float t = ((pt.X - p1.X) * dx + (pt.Y - p1.Y) * dy) / (dx * dx + dy * dy);

// See if this represents one of the segment's
// end points or a point in the middle.
if (t < 0)
{
closest = new PointF(p1.X, p1.Y);
dx = pt.X - p1.X;
dy = pt.Y - p1.Y;
}
else if (t > 1)
{
closest = new PointF(p2.X, p2.Y);
dx = pt.X - p2.X;
dy = pt.Y - p2.Y;
}
else
{
closest = new PointF(p1.X + t * dx, p1.Y + t * dy);
dx = pt.X - closest.X;
dy = pt.Y - closest.Y;
}

return Math.Sqrt(dx * dx + dy * dy);
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.