Clonkex
Clonkex

Reputation: 3637

Calculate how much smaller a square would have to be to fit after rotated 45 degrees

Background: I'm creating a UI element in Unity and need to rotate it. It's a square, and will be rotated 45 degrees. Since rotation in Unity's UI happens after all sizing and positioning is done, the corners of this square stick outside the maximum area.

So I have a square inside a square. By default it's the same size as the parent square. After rotating 45 degrees, it's too large to fit in the parent square. How do I calculate the percentage by which to scale down the child square before rotating to make it fit inside the parent square after rotating?

enter image description here

Upvotes: 4

Views: 3868

Answers (2)

walnut
walnut

Reputation: 22152

A square of edge length a has a diagonal of length d = sqrt(2)*a, because, by Pythagoras theorem, the triangle formed by the diagonal and two of the square's edges satisfies d^2 = a^2 + a^2 = 2*a^2.

Therefore the inner square must be scaled by 1/sqrt(2) which is identical to sin(pi/4) = sin(45°) and cos(pi/4) = cos(45°) and approximately 0.7071....

If the scaling is performed centered at the sqaure's center, it doesn't matter whether rotation happens before or after scaling.

Upvotes: 2

Clonkex
Clonkex

Reputation: 3637

Actually, I just figured it out. The size of the child square needs to be a percentage of the parent square's size, which we can get from the sine (or cosine also works, I think?) of 45 degrees.

sin(45) == 0.70710678118654752440084436210485

To get to that size, I need to reduce my child square's size by the difference between 100% and 70.7106...%.

1 - sin(45) == 0.29289321881345247559915563789515

Since I'm using Unity and controlling the size of my square UI element with anchor positions, I just divided that by 2 and set the min X anchor to 0.146 and the max X anchor to 0.854. With an Aspect Ratio Fitter component set to Width Controls Height and a ratio of 1, this causes my child square to always fit perfectly inside my parent square even when rotated.

Upvotes: 2

Related Questions