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

663
2024/8/30 9:31:01
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要在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()方法将角度转换为弧度。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java中的stringtokenizer怎么使用