如何在Java中實(shí)現(xiàn)正方形的旋轉(zhuǎn)

小樊
82
2024-08-30 07:25:30

要在Java中實(shí)現(xiàn)正方形的旋轉(zhuǎn),你可以使用Java2D圖形庫(kù)

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);

        // 設(shè)置正方形的位置和大小
        int squareX = 100;
        int squareY = 100;
        int squareWidth = 100;
        int squareHeight = 100;

        // 創(chuàng)建一個(gè)新的AffineTransform對(duì)象,用于存儲(chǔ)旋轉(zhuǎn)信息
        AffineTransform transform = new AffineTransform();

        // 設(shè)置旋轉(zhuǎn)的角度(以弧度為單位)
        double rotationAngle = Math.toRadians(45);

        // 將原點(diǎn)移動(dòng)到正方形的中心,以便圍繞中心旋轉(zhuǎn)
        transform.translate(squareX + squareWidth / 2, squareY + squareHeight / 2);

        // 應(yīng)用旋轉(zhuǎn)
        transform.rotate(rotationAngle);

        // 將原點(diǎn)移回到正方形的左上角
        transform.translate(-squareX - squareWidth / 2, -squareY - squareHeight / 2);

        // 將變換應(yīng)用于Graphics2D對(duì)象
        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);
        });
    }
}

這個(gè)示例創(chuàng)建了一個(gè)窗口,并在其中繪制了一個(gè)旋轉(zhuǎn)的正方形。通過(guò)修改rotationAngle變量,你可以改變正方形的旋轉(zhuǎn)角度。請(qǐng)注意,這個(gè)示例使用了弧度作為角度單位,因此我們使用Math.toRadians()方法將角度轉(zhuǎn)換為弧度。

0