Java rotates a rectangle around the center

I would like to rotate the rectangle around its center point, and it should remain in the place that is supposed to be drawn and rotated in this space

this is my code:

AffineTransform transform = new AffineTransform(); transform.rotate(Math.toRadians(45),rectangle.width/2, rectangle.height/2); Shape transformed = transform.createTransformedShape(rectangle); g2.fill(transformed) 

the rectangle rotates, but it is drawn in another part of the screen, how can I fix this?

+6
source share
2 answers

I have not tried this, but it seems that you are not getting the correct middle of the rectangle. Try:

 AffineTransform transform = new AffineTransform(); transform.rotate(Math.toRadians(45), rectangle.getX() + rectangle.width/2, rectangle.getY() + rectangle.height/2); g2.fill(transformed); 

The difference is that now you add the width to the starting point X and add the height to the starting point Y, and therefore to the middle of the rectangle.

Hope this helps.

+12
source
 AffineTransform transform = new AffineTransform(); transform.rotate(theta, rect.getX() + rect.width/2, rect.getY() + rect.height/2); AffineTransform old = g2.getTransform(); g2.transform(transform); // draw your rectangle here... g2.setTransfrom(old); 

If you do it this way, you can draw a more advanced rectangle. For example, with a fill gradient or text inside a rectangle. Everything will spin with it.

+5
source

Source: https://habr.com/ru/post/905643/


All Articles