Seems like there should be some convenient way to do this?
I couldn’t find one, so I threw together the below algorithm. Is it memory/computationally optimal?
Thanks:
Edit: Original algorithm was stupidly wrong, maybe this is better?
public static float minDistance(RectF rect, PointF point)
{
if(rect.contains(point.x, point.y))
{
//North line
float distance = point.y - rect.top;
//East line
distance = Math.min(distance, point.x - rect.left);
//South line
distance = Math.min(distance, rect.bottom - point.y);
//West line
distance = Math.min(distance, rect.right - point.x);
return distance;
}
else
{
float minX, minY;
if (point.x < rect.left)
{
minX = rect.left;
}
else if (point.x > rect.right)
{
minX = rect.right;
}
else
{
minX = point.x;
}
if (point.y < rect.top)
{
minY = rect.top;
}
else if (point.y > rect.bottom)
{
minY = rect.bottom;
}
else
{
minY = point.y;
}
float vectorX = point.x - minX;
float vectorY = point.y - minY;
float distance = (float) Math.sqrt((vectorX * vectorX) + (vectorY * vectorY));
return distance;
}
}
Just take the closest point and then get the distance to that.
Off the top of my head: