10

I have drawn some Graphics in a JPanel, like circles, rectangles, etc.

But I want to draw some Graphics rotated a specific degree amount, like a rotated ellipse. What should I do?

tckmn
  • 57,719
  • 27
  • 114
  • 156
KidLet
  • 173
  • 1
  • 2
  • 5

2 Answers2

30

If you are using plain Graphics, cast to Graphics2D first:

Graphics2D g2d = (Graphics2D)g;

To rotate an entire Graphics2D:

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

To reset the rotation (so 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
    }
}
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • Thans you very much and How to trasnlate a new position from old AffineTransform ? – KidLet Jan 02 '13 at 15:40
  • @KidLet This might help: http://docs.oracle.com/javase/7/docs/api/java/awt/geom/AffineTransform.html You can use `rotate`, `scale`, and `translate`. – tckmn Jan 02 '13 at 15:42
3

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

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255