[Math] Given the width and rotation of rectangle, calculate it’s unrotated width

geometrytrigonometry

In web graphics if you ask for the width property of a rectangle you'll get back the horizontal measurement of the rectangle at that time rather than it's starting width. So a rectangle that is longer than tall will return a shorter width measurement when it is rotated.

I'd like to measure it's unrotated width.

I thought I had a solution with the code below, however it works for all angles except at 45, -45, 135, and -135.

public static function width( designObject:DisplayObject ):Number
{
    // convert degrees to radians
    var r:Number = designObject.rotation * Math.PI/180;
    // cos, c in the equation
    var c:Number = Math.abs(Math.cos(r));
    // sin, s in the equation
    var s:Number = Math.abs(Math.sin(r));
    // get the unrotated width
    var w:Number = (designObject.width * c - designObject.height * s) / (Math.pow(c, 2) - Math.pow(s, 2));

    return w;
}

Using the code above a rectangle that is 148.2 pixels wide returns that width for all angles, but at 45 degrees it returns 64. Am I missing something, might there be an alternate solution?

thanks!

Best Answer

It's probably bugging out because $\cos 45^\circ = \sin 45^\circ$, so the denominator becomes zero. I can't imagine why it would return exactly $64$ though.

In any case, there probably isn't any way to do it for exactly $45^\circ$. For any given square, there are lots of rectangles of different sizes that fit exactly in it at $45^\circ$. So just from knowing the size of the square, you can't recover the dimensions of the rectangle. You can do it if you know the aspect ratio of the rectangle, though.