There exists a method to find the closest distance from circle to rectangle (axis-oriented here).
Rectangle sides divide plane into 9 pieces. We can find what piece (central, left-top, left etc) contains circle center, and calculate needed distance. Rectangle ABCD and circle center E:
Delphi code:
//returns closest distance from circle to rectangle
//0 if intersection or inclusion occurs
function CircleRectDistance(CX, CY, CR: Integer; RR: TRect): Double;
var
wh, hh, dx, dy, t, SquaredDist: Double;
begin
SquaredDist := 0;
//halfwidth and halfheight
wh := 0.5 * (RR.Right - RR.Left);
hh := 0.5 * (RR.Bottom - RR.Top);
//distances to rectangle center
dx := CX - 0.5 * (RR.Left + RR.Right);
dy := CY - 0.5 * (RR.Top + RR.Bottom);
//rectangle sides divide plane to 9 parts,
t := dx + wh;
if t < 0 then
SquaredDist := t * t
else begin
t := dx - wh;
if t > 0 then
SquaredDist := t * t
end;
t := dy + hh;
if t < 0 then
SquaredDist := SquaredDist + t * t
else begin
t := dy - hh;
if t > 0 then
SquaredDist := SquaredDist + t * t
end;
if SquaredDist < CR * CR then
Result := 0
else
Result := Sqrt(SquaredDist)- CR;
end;