12. Point-segment distance

There are two cases to consider when solving this problem. First, the point on the segment that is closest to the target point might lie on the line segment. In that case, Solution 30 solves this problem.

The second case occurs if the point found by Solution 30 does not lie on the segment but only lies on the line that contains the segment. In that case, the point on the segment that is closest to the point is one of the segment's endpoints.

The following PointSegmentClosestPoint method finds the point on a segment that is closest to the target point. It also returns a Boolean through the isOnSegment output parameter, indicating whether that point lies on the segment:

// Find the point on the line p0-p1 that is closest to point p.
private PointF PointSegmentClosestPoint(PointF p, PointF p0, PointF p1,
out bool isOnSegment)
{
float vx = p1.X - p0.X;
float vy = p1.Y - p0.Y;
float numerator = vx * (p.X - p0.X) + vy * (p.Y - p0.Y);
float denominator = vx * vx + vy * vy;
float t = numerator / denominator;

// See if the point is on the segment.
isOnSegment = ((t >= 0) && (t <= 1));
if (isOnSegment) return new PointF(p0.X + t * vx, p0.Y + t * vy);

// The point we found is not on the segment.
// See which end point is closer.
float dx0 = p.X - p0.X;
float dy0 = p.Y - p0.Y;
float dist0squared = dx0 * dx0 + dy0 * dy0;

    float dx1 = p.X - p1.X;
float dy1 = p.Y - p1.Y;
float dist1squared = dx1 * dx1 + dy1 * dy1;

if (dist0squared <= dist1squared) return p0;
return p1;
}

This method uses the technique used by Solution 30 to find the point on the segment's line that is closest to the target point. If the parameter t lies between 0 and 1, then this point also lies on the segment so the method returns it.

If t does not lie between 0 and 1, the method calculates the distances squared between the segment's endpoints and the target point. It then returns whichever endpoint is closer to the target point.

Download the PointSegmentDistance example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.121.81