Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to rotate a rectangle

Tags:

math

geometry

I'm using rectangles defined in terms of their x y coordinates and their width and height. I figured out how to rotate them in terms of coordinates (x = cos(deg) * x - sin(deg) * y y = sin(deg) * x + cos(deg) * y) but I'm stuck on the height and width. I'm sure there's an obvious solution that I'm missing. If it matters, I'm using Python.

edit Sorry for the confusing description. My intention is to get the width and height either reversed or negated due to whatever the angle is. For example, in a 90 degree rotation the values would switch. In a 180 degree rotation the width would be negative. Also, I only intend to use multiples of 90 in my script. I could just use if statements, but I assumed there would be a more "elegant" method.

like image 312
tankadillo Avatar asked Feb 18 '10 02:02

tankadillo


1 Answers

Just calculate four corners of Your rectangle:

p1 = (x, y)
p2 = (x + w, y)
p3 = (x, y + h)

and rotate each by angle You want:

p1 = rotate(p1, angle)
# and so on...

and transform back to Your rectangle representation:

x, y = p1
w = dist(p1, p2)  # the same as before rotation
h = dist(p1, p3)

where dist calculates distance between two points.

Edit: Why don't You try apply formula You have written to (width, height) pair?

x1 = cos(deg) * x - sin(deg) * y
y2 = sin(deg) * x + cos(deg) * y

It is easy to see that if deg == 90 the values will switch:

x1 = -y
y2 =  x

and if deg == 180 they will be negated:

x1 = -x
y2 = -y

and so on... I think this is what You are looking for.

Edit2:

Here comes fast rotation function:

def rotate_left_by_90(times, x, y):
    return [(x, y), (-y, x), (-x, -y), (y, -x)][times % 4]
like image 51
Dawid Avatar answered Nov 10 '22 06:11

Dawid