0
$\begingroup$

In x,y space, given a coordinate P that is within bounds 0,0,bWidth,bHeight and a rectangle r where r has width rWidth and rHeight (and rWidth<=bWidth and rHeight<=bHeight), present an algorithm that would return the coordinates of a rectangle T such that T has the same width and height of r and is contained in the bounds and is as close to centered around P as possible.

ie, if p is top left point, then T would be in the top left, but if P is in middle, so is T.

is there any way of doing this without having to do a bunch of if statements?

$\endgroup$
1
$\begingroup$

The $x$ coordinate of the center of the translated rectangle should ideally be $P_x$, but must be at least $\frac{\mathit{rWidth}}2$ and at most $\mathit{bWidth}-\frac{\mathit{rWidth}}2$:

$$ C_x = \min(\max(P_x,\frac{\mathit{rWidth}}2),\mathit{bWidth}-\frac{\mathit{rWidth}}2)$$

Similarly for the $y$ coordinate.

Of course, the $\min$ and $\max$ have conditionals hidden within them, e.g.: $$\min(a,b) = \begin{cases}a & \text{if } a<b \\ b & \text{otherwise}\end{cases}$$ There's no real way around this for getting the necessary sharp edges in the output. If you really want, you can disguise the conditionals using absolute values: $$ \min(a,b) = \frac{a+b-|a-b|}2 $$ but that will just make the expressions impenetrable without really buying you anything valuable.

$\endgroup$
1
$\begingroup$

You only need four if statements as far as I can tell. In pseudocode,

rX = pX - rWidth/2;
rY = pY - rHeight/2;

if(rX < 0){
    rX = 0;
}
else if(rX + rWidth > bWidth){
    rX -= (rX + rWidth) - bWidth;
}

if(rY < 0){
    rY = 0;
}
else if(rY + rHeight > bHeight){
    rY -= (rY + rHeight) - bHeight;
}

rX, rY are coordinates of the corner of the rectangle closest to the origin. (Top left in computer graphics, lower left in the first quadrant of an XY graph)

I think that if statements like this are very common in graphics computing, although I am not an expert.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.