This is actually something I'm doing in Objective-C programming, but since it's very math-oriented I thought I'd post it here.
I was reading up on linear transformations: http://en.wikipedia.org/wiki/Matrix_(mathematics)
Basically I need to rotate a shape around its center. With my current implementation, the rotation is done using the top left as its origin. Here's a screenshot:
Here's the code I'm using to create each x,y coordinate:
CGFloat angle = 0.261799; // (15 degrees)
CGFloat xr = x1 * cosf(angle) + y1 * -sinf(angle) + tx;
CGFloat yr = x1 * sinf(angle) + y1 * cosf(angle) + ty;
I realize there are functions (CGAffineTransformRotate, etc) in Objective-C that do this for me, but since I'm not using a UIView, I need to do it manually. Plus, it would be nice to know. 🙂
So when I plug in 35.0 for tx and -35.0 for ty, (numbers I just found that seemed to work, through trial and error) here is what I get:
That's what I want! Now I just need some way to figure out these tx
and ty
translation values to center the shape's origin, based on the given angle, width or height values. (I'm also seeing different results when setting tx
and ty
if the original x,y coordinates of the shape are different.)
Any help would be much appreciated. Thanks!
Best Answer
Let xc, yc be the coordinates of the center of the rectangle.
Translate your points such that the center is the new origin:
Rotate around the origin by the angle a:
Translate points back:
If you do this for all 4 corners of the rectangle and then draw lines between the transformed corners, you get the rotated rectangle. The rotation angle $a$ is measured from the x-axis ($0$) to to the y-axis ($\pi/2$). In 2D graphic libraries the x-axis goes to the right and the y-axis goes down, such that the angle $+35^\circ$ corresponds to your figure.