calculating distance between a point and a rectangular box (nearest point)

前端 未结 9 1747
广开言路
广开言路 2020-12-13 06:25

is there a easy formula to calculate this? i\'ve been working on some math but i can only find a way to calculate the distance directed to the center of the box, not direct

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 06:58

    Lightly optimized C# alternative (although there should probably be some tolerance when comparing doubles against 0). I also recommend creating some kind of Rect or Point extension methods for these.

    public static class GeometryUtils
    {
        public static double Distance(Point point, Rect rect)
        {
            var xDist = MinXDistance(point, rect);
            var yDist = MinYDistance(point, rect);
            if (xDist == 0)
            {
                return yDist;
            }
            else if (yDist == 0)
            {
                return xDist;
            }
    
            return Math.Sqrt(Math.Pow(xDist, 2) + Math.Pow(yDist, 2));
        }
    
        private static double MinXDistance(Point point, Rect rect)
        {
            if (rect.Left > point.X)
            {
                return rect.Left - point.X;
            }
            else if (rect.Right < point.X)
            {
                return point.X - rect.Right;
            }
            else
            {
                return 0;
            }
        }
    
        private static double MinYDistance(Point point, Rect rect)
        {
            if (rect.Bottom < point.Y)
            {
                return point.Y - rect.Bottom;
            }
            else if (rect.Top > point.Y)
            {
                return rect.Top - point.Y;
            }
            else
            {
                return 0;
            }
        }
    }
    

提交回复
热议问题