温馨提示×

如何在Java中实现正方形的旋转

小樊
82
2024-08-30 07:25:30
栏目: 编程语言

要在Java中实现正方形的旋转,你可以使用Java2D图形库

import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;

public class SquareRotationExample extends JFrame {
    public SquareRotationExample() {
        setTitle("Square Rotation Example");
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 设置正方形的位置和大小
        int squareX = 100;
        int squareY = 100;
        int squareWidth = 100;
        int squareHeight = 100;

        // 创建一个新的AffineTransform对象,用于存储旋转信息
        AffineTransform transform = new AffineTransform();

        // 设置旋转的角度(以弧度为单位)
        double rotationAngle = Math.toRadians(45);

        // 将原点移动到正方形的中心,以便围绕中心旋转
        transform.translate(squareX + squareWidth / 2, squareY + squareHeight / 2);

        // 应用旋转
        transform.rotate(rotationAngle);

        // 将原点移回到正方形的左上角
        transform.translate(-squareX - squareWidth / 2, -squareY - squareHeight / 2);

        // 将变换应用于Graphics2D对象
        g2d.setTransform(transform);

        // 绘制正方形
        g2d.setColor(Color.BLUE);
        g2d.fillRect(squareX, squareY, squareWidth, squareHeight);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SquareRotationExample frame = new SquareRotationExample();
            frame.setVisible(true);
        });
    }
}

这个示例创建了一个窗口,并在其中绘制了一个旋转的正方形。通过修改rotationAngle变量,你可以改变正方形的旋转角度。请注意,这个示例使用了弧度作为角度单位,因此我们使用Math.toRadians()方法将角度转换为弧度。

0