sqrt(min(|x1 - x2|, w - |x1 - x2|)^2 + min(|y1 - y2|, h - |y1-y2|)^2)
Where the two points are
hare the width and height;
sqrtare minimization and square root functions, respectively.
With that the process is absurdly easy.
Note: If you just need relative distance for a comparison, don't bother using the square root.
Function courtesy of: