Thanks for the help on this.
I created two functions to solve my problem. There might be an easy way, but these functions solved my purpose.
FindNearestPointOntheSegment: To find the nearest point on the segment.
private Point FindNearestPointOntheSegment(Point pt1, Point pt2, Point pt)
{
double m = (double)(pt2.Y - pt1.Y) / (pt2.X - pt1.X); //slope
double c = (double)pt1.Y - (m * pt1.X); //intercept
//Get nearest point on the line
//ttp://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html"
double x = (m * pt.Y + pt.X - m * c) / (m * m + 1);
double y = (m * m * pt.Y + m * pt.X + c) / (m * m + 1);
return new Point(x, y);
}
//IsPointOnSegment: To find, is the projected point on the segment or not.
private bool IsPointOnSegment(Point pt1, Point pt2, Point pt)
{
//y= mx+c
//ttp://www.softwareandfinance.com/Turbo_C/Check_Point_Lies_line_Segment.html
double m = (pt2.Y-pt1.Y) / (pt2.X-pt1.X); //Slope
double c = pt1.Y - (m * pt1.X); //intercept
//Create bounding box
double left;
double right;
double top;
double bottom;
if (pt1.X < pt2.X) { left = pt1.X; right = pt2.X;}
else{left = pt2.X;right = pt1.X;}
if (pt1.Y < pt2.Y){top = pt1.Y;bottom = pt2.Y;}
else{top = pt2.Y;bottom = pt1.Y;}
// Checking if pt is on the line passing through the end points.
if (((m * pt.X + c) > (pt.Y - 0.001)) && ((m * pt.X + c) < (pt.Y + 0.001)))
{
if ((pt.X >= left && pt.X <= right) && pt.Y >= top && pt.Y < bottom)
return true;
else
return false;
}
else
{
return false;
}
}