围绕 x 轴垂直旋转形状
提供的代码演示了如何旋转多边形,但它不会围绕 x 轴旋转它x 轴。要实现绕 x 轴的垂直旋转,我们可以将多边形旋转 90 度,然后应用所需的弧度旋转。修改后的代码如下:
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();
}
}
在此代码中,我们在 PaintComponent 方法中使用 g2d.rotate(Math.PI / 2, w / 2, h / 2) 将多边形旋转 90 度。这会将多边形与 x 轴对齐,允许我们使用 g2d.rotate(theta, w / 2, h / 2).
应用所需的弧度旋转免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3