Search code examples
mathrotationgeometrybounding-boxcoordinate-transformation

Calculate rotated rectangle transform using bounding box coordinates


I have a Red container rotated by -13 degrees, inside this container there is a Pink Square also rotated by -13 degrees.

enter image description here

Using only these informations below I'm trying to find the pink square transform relative to the origin (top,left) (0,0)

The relative transform coordinate is how much I need to translate inside the parent. And the bounding box is just the size with rotation included (it's the black box on the screenshot)

Pink Square

size before rotation
height : 398
width : 398

size after rotation
height : 477
width : 477

Bounding box
x : 179
y : 230

Relative transform to parent
x : 0
y : 49

Rotation 

-13 deg

Red Container

size before rotation
height : 632
width : 447

size after rotation
height : 716
width : 577

Bounding box
x : 179
y : 182.28

Relative transform to parent
x : 279
y : 182

Rotation 

-13 deg

Here is what I tried to do

yCoordinate = pink.relativeTransform.y + redContainer.boundingBox.y
xCoordinate = pink.relativeTransform.x + redContainer.boundingBox.x

I managed to get the yCoordinate right but I can't get the x coordinate also I'm worried that this will works for all angles


Solution

  • If you represent the transforms as matrices, you will get the answer pretty easily (note that I will use the word transform to denote the entire transformation, including rotations, and not just the offset vector). Btw, your image shows a rotation in positive direction (in a mathematical sense), so I will assume that it is actually +13°.

    To get the transformation matrix for a rotation of angle phi and offset vector (tx, ty), we can employ the following form:

        / cos(phi)  -sin(phi)  tx \
    T = | sin(phi)   cos(phi)  ty |
        \    0           0      1 /
    

    Hence, the transformation of the red rectangle with respect to the origin would be:

           / 0.974  -0.225  279 \
    TRed = | 0.225   0.974  182 |
           \   0       0     1  /
    

    The transformation of the pink square with respect to the red rectangle would be (no rotation relative to parent, just a translation):

            / 1 0  0 \
    TPink = | 0 1 49 |
            \ 0 0  1 /
    

    To get the transformation of the pink square with respect to the origin, we just multiply the two matrices:

                   / 0.974  0.225  267.977 \
    TRed * TPink = | 0.225  0.974  229.744 |
                   \   0      0      1     /
    

    We can see that the first part is the same rotation as in TRed, i.e., a rotation by 13°. The translation (which is the vector you are looking for) is (267.977, 229.744).

    In general, this translation vector is:

    /  cos(phi) * tPinkX - sin(phi) * tPinkY + tRedX \
    \  sin(phi) * tPinkX + cos(phi) * tPinkY + tRedY /