Search code examples
javaswinggraphics2d

Graphics2D - Rotating Shapes on a Graphics2D object


I have a Graphics2D object which I use to draw on my Canvas. I draw multiple shapes on the Canvas and want to transform only one (or part) of them.

I'll try to keep this simple:

void render(Graphics2D g) {
    ... // Draw shape 1
    ... // Draw shape 2
    ... // Draw shape 3
}

How would I go about rotating shape 2 while leaving shape 1 and 3 intact? By "rotate" I mean rotating around its center point, which we can define as x and y for example.

I've been looking for a way to do this for a while now, but couldn't find anything that works the way I want it to.

Is there any simple way to do this?


Solution

  • Rather than rotating the shape around it's centre point, rotate and then translate the canvas. To rotate around the centre of the shape at (x, y), first translate the canvas by (-x, -y) and then rotate the canvas -d degrees and draw the shape as normal at (0,0).

    When you're done, rotate back then translate back (note that with these geometric transformations the order is important, translating and then rotating will give you a completely different outcome).

    This means that you can still draw an object at any rotation without having to recalculate the coordinates yourself.