user6419081
user6419081

Reputation: 21

Rotating rectangles so they maintain their relative position to the canvas

I have a background pixmap, basically a canvas, which I draw a bunch of rectangles on and I need to rotate the pixmap and rectangles. However rotating the background pixmap and the rectangles needs to be done seperately, that is the rotation of the background pixmap gets handled via an external library routine and I need to rotate and redraw the rectangles on top manually.

So far I am actually able to rotate the rectangles by applying a transformation matrix I got from Wikipedia to each vertex. What I don't know is how to translate them that each rectangle retains its position relative to the canvas.

Here is a quick drawing for illustration of what I want to achieve: enter image description here

I need to do this with C and Xlib, but I'm not necessarily looking for code but would appreciate some general hints/algorithms.

Upvotes: 1

Views: 285

Answers (1)

vgru
vgru

Reputation: 51214

To get the translated position for the child object, you need to rotate the relative position vector for the child object, and then add it to the origin:

Notice that the relative vector is rotated

Pseudocode would be:

public static Vector2 OffsetByRotation(Vector2 childPos, Vector2 parentPos, float angle)
{
    var relativeVector = childPos - parentPos;
    relativeVector = Rotate(relativeVector, angle);
    return parentPos + relativeVector;
}

Note that your example image not only rotates the parent object, but also translates it: your left image is rotated around (0, 300), but this point is then translated to (0, 0).

enter image description here

Upvotes: 3

Related Questions