How to rotate graphics in Java

I drew some graphics in JPanel like circles, rectangles, etc.

But I want to draw some graphics rotated to a certain degree, like a rotated ellipse. What should I do?

+4
source share
2 answers

If you are using plain Graphics , first type Graphics2D :

 Graphics2D g2d = (Graphics2D)g; 

To rotate an integer Graphics2D :

 g2d.rotate(Math.toRadians(degrees)); //draw shape/image (will be rotated) 

The reset rotation (so that you only rotate one thing):

 AffineTransform old = g2d.getTransform(); g2d.rotate(Math.toRadians(degrees)); //draw shape/image (will be rotated) g2d.setTransform(old); //things you draw after here will not be rotated 

Example:

 class MyPanel extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; AffineTransform old = g2d.getTransform(); g2d.rotate(Math.toRadians(degrees)); //draw shape/image (will be rotated) g2d.setTransform(old); //things you draw after here will not be rotated } } 
+19
source

In your overridden paintComponent() method, move the Graphics argument to Graphics2D, call rotate() on that Graphics2D, and draw an ellipse.

+3
source

All Articles