Rotate an image in java by the specified angle
Asked Answered
S

2

2

Here's the function which draws a shape at the given coordinates:

public void drawTank(int x,int y){
   int h = 50;
   int w = 50;

   graphic.setColor(Color.darkGray);
   graphic.drawRect(x, y, h, w);
   graphic.fillRect(x, y, h, w);
   graphic.setColor(Color.GRAY);
   graphic.drawRect(x+50, y+20, 35, 10);
   graphic.fillRect(x+50, y+20, 35, 10);
}

I want to add one more variable to the above function called 'angle', so that the image is also rotated by the angle specified (drawTank(int x,int y,int angle).

Updated with example

What I tried to do is that I initialized Graphics2D and changed my code respectively:

g2D.setColor(Color.darkGray);
g2D.drawRect(x, y, h, w);
g2D.fillRect(x, y, h, w);
g2D.setColor(Color.red);
g2D.drawRect(x+50, y+20, 35, 10);
g2D.fillRect(x+50, y+20, 35, 10);
g2D.rotate((Math.toRadians(angle)));

But, this doesn't actually do anything. :/

Strongminded answered 14/2, 2013 at 21:35 Comment(1)
1) If the graphic variable is a Graphics2D object, consider using an AffineTransform on the Graphics object. 2) Shouldn't this method have a Graphics or better a Graphics2D parameter so that the current active Graphics object can be passed in from the JComponent's paintComponent(Graphics g) method (if Swing)?Pretext
O
2

Precedence matters...

In your second example, you're apply a rotation AFTER you've drawn everything. This is not how graphics works. You need to apply the transformation first, then everything that follows will use that transformation.

enter image description here

public class TestRotateImage {

    public static void main(String[] args) {
        new TestRotateImage();
    }

    public TestRotateImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JSlider slider;
        private Rectangle rectangle;

        public TestPane() {
            setLayout(new BorderLayout());
            rectangle = new Rectangle(0, 0, 100, 100);
            slider = new JSlider();
            slider.setMinimum(0);
            slider.setMaximum(360);
            slider.setMinorTickSpacing(5);
            slider.setMajorTickSpacing(10);
            slider.setValue(0);
            add(slider, BorderLayout.SOUTH);
            slider.addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    repaint();
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        public double getAngle() {

            return Math.toRadians(slider.getValue());

        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();

            g2d.setColor(Color.RED);
            g2d.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());
            g2d.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);

            g2d.setColor(Color.BLACK);
            int x = (getWidth() - rectangle.width) / 2;
            int y = (getHeight() - rectangle.height) / 2;
            AffineTransform at = new AffineTransform();
            at.setToRotation(getAngle(), x + (rectangle.width / 2), y + (rectangle.height / 2));
            at.translate(x, y);
            g2d.setTransform(at);
            g2d.draw(rectangle);
            g2d.dispose();

        }

    }

}

You might like to take a look at Transforming Shapes, Text and Images for more information

Onto answered 14/2, 2013 at 23:0 Comment(2)
Yep, copy the Graphics so that you don't have to re-set the transform.Pretext
@HovercraftFullOfEels Yep, +1 for being lazy ;)Onto
V
0

Here's the brute-force way to do it. Take a look at Java.lang.Math and java.awt.Graphics (which you already have an instance of) With this you can use the draw polygon function to compute the points of your rectangle, which you can do using the sin and cos functions in Java.lang.Math

Really, you'd only need to compute two points this way, as your starting point would be the 90degree vertex from which you would calculate the two adjoining coordinates with. From there it's just a matter of doing some addition and subtraction with the points that you have and your dimension values to get the last point kitty-corner to your starting point.

I'd figure it out for you, and write some example code, but then what fun would that leave you?

Venegas answered 14/2, 2013 at 21:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.