[Math] How to calculate the new x y coordinate for a rectangle when centering it within a rectangle

geometrylinear algebra

I need to center a rectangle inside another rectangle. I know the width and height of the parent rectangle, and I know the width and height of the child rectangle that needs to be centered. I need to find the x and y coordinate for the top left corner of the rectangle in the centered position. I don't know the current position of the child recatangle, I just need know the x y coordinate so I can place it in the center.

Please see the image below for further details.

What would be the correct formula to do this?

Example

Best Answer

If the big rectangle is $a \times b$ (in your diagram $a=26, b=305$), and the smaller rectangle is $c \times d$ (here $(c,d)=(18,68)$), then your $x,y$ satisfy $2x+c=a,2y+d=b$ so that $(x,y)=((a-c)/2,(b-d)/2).$

A check: $(x,y)=(4,118.5)$ so the check would be $4+18+4=26$ and $118.5+68+118.5=305.$

Related Question