如何在Java2D中旋转矩形

时间:2012-11-26 20:56:10

标签: java java-2d

我想在方法中旋转一个矩形但不明白如何操作并尝试如下:

private void setBoundaryRotate(Rectangle b, int radio) {
        AffineTransform transform = new AffineTransform();
        transform.rotate(Math.toRadians(45), b.getX() + b.width/2, b.getY() + b.height/2);}

谢谢大家。

2 个答案:

答案 0 :(得分:1)

您需要在transform对象上调用transform()方法,将矩形的坐标传入数组中。

答案 1 :(得分:0)

这有点主观,这完全取决于你想要实现的目标。

以下代码使用AffineTransform来旋转矩形,但为了做到这一点,我需要获得PathIterator并将其添加回Path2D

public class SpinBox {

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

    public SpinBox() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new SpinPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class SpinPane extends JPanel {

        private Rectangle box = new Rectangle(0, 0, 100, 100);
        private float angle = 0;

        public SpinPane() {
            Timer timer = new Timer(1000/60, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    angle += 1;
                    repaint();
                }
            });
            timer.setRepeats(true);
            timer.start();
        }

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

        @Override
        protected void paintComponent(Graphics g) {

            super.paintComponent(g);

            int width = getWidth() - 1;
            int height = getHeight() - 1;

            int x = (width - box.width) / 2;
            int y = (height - box.height) / 2;

            Graphics2D g2d = (Graphics2D) g.create();
            AffineTransform at = new AffineTransform();
            at.rotate(Math.toRadians(angle), box.x + (box.width / 2), box.y + (box.height / 2));
            PathIterator pi = box.getPathIterator(at);
            Path2D path = new Path2D.Float();
            path.append(pi, true);
            g2d.translate(x, y);
            g2d.draw(path);
            g2d.dispose();

        }

    }

}