Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate Graphics in Java

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?

like image 466
KidLet Avatar asked Jan 02 '13 15:01

KidLet


People also ask

How do you rotate a label in Java?

A JLabel can explicitly generate a PropertyChangeListener interface. By default, JLabel can display a text in the horizontal position and we can rotate a JLabel text by implementing the rotate() method of Graphics2D class inside the paintComponent().

What is rotate in Java?

rotate() method is present in java. util. Collections class. It is used to rotate the elements present in the specified list of Collection by a given distance. Syntax: public static void rotate(List< type > list, int distance) Parameters : list - the list to be rotated.


1 Answers

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
    }
}
like image 140
tckmn Avatar answered Nov 15 '22 22:11

tckmn