首頁 > Java > java教程 > 主體

如何在 Java 中繞 x 軸垂直旋轉形狀?

DDD
發布: 2024-10-27 21:35:30
原創
279 人瀏覽過

How can I rotate a shape vertically around the x-axis in Java?

繞 x 軸垂直旋轉形狀

提供的程式碼示範如何旋轉多邊形,但它不會圍繞它旋轉x 軸。要實現繞 x 軸的垂直旋轉,我們可以將多邊形旋轉 90 度,然後套用所需的弧度旋轉。以下是修改後的程式碼:

<code class="java">import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RotatingShape extends JPanel implements ActionListener {

    private int[] p1x = {200, 200, 240, 240, 220, 220, 200};
    private int[] p1y = {200, 260, 260, 240, 240, 200, 200};
    private Polygon p1 = new Polygon(p1x, p1y, p1x.length);
    private double theta = 0;
    private double dt = Math.PI / 36; // Rotation speed
    private Timer timer = new Timer(100, this);

    public RotatingShape() {
        this.setPreferredSize(new Dimension(700, 700));
        this.setBackground(Color.white);
        p1.translate(-50, +100);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        theta += dt;
        repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        int w = this.getWidth();
        int h = this.getHeight();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.drawLine(w / 2, 0, w / 2, h);
        g2d.drawLine(0, h / 2, w, h / 2);
        g2d.rotate(Math.PI / 2, w / 2, h / 2); // Rotate 90 degrees to align with x-axis
        g2d.rotate(theta, w / 2, h / 2); // Apply rotation around x-axis
        g2d.drawPolygon(p1);
    }

    public void start() {
        timer.start();
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Rotating Shape");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        RotatingShape sl = new RotatingShape();
        frame.add(sl);
        frame.pack();
        frame.setVisible(true);
        sl.start();
    }
}</code>
登入後複製

在此程式碼中,我們在PaintComponent 方法中使用g2d.rotate(Math.PI / 2, w / 2, h / 2) 將多邊形旋轉90 度。這會將多邊形與 x 軸對齊,從而允許我們使用 g2d.rotate(theta, w / 2, h / 2) 應用所需的弧度旋轉。

以上是如何在 Java 中繞 x 軸垂直旋轉形狀?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!