【问题标题】:Java GUI Rotation and Translation of RectangleJava GUI 旋转和平移矩形
【发布时间】:2012-12-15 23:27:05
【问题描述】:

我正在尝试在 JPanel 中绘制一个矩形,该矩形将平移然后自行旋转以模仿汽车的运动。我已经能够使矩形平移和旋转,但是它围绕(0,0)的原点旋转。我很高兴我能够让矩形移动和旋转,因为我对 Java GUI 很陌生,但我似乎不知道如何让矩形围绕自身旋转,因为我对它进行了更多实验,以及何时我初始化了矩形并将其旋转 45 度,它的位置发生了变化,我认为这是从旋转方法附加的变换矩阵。

我在网站上查看了如何解决这个问题,但是我只找到了如何旋转一个矩形,而不是如何像模拟汽车的运动一样旋转和移动。我认为它与它的变换矩阵有关,但我只是在推测。所以我的问题是我如何才能让矩形能够旋转和移动,而不是靠在 JPanel 中的一个点上。

这是我到目前为止提出的代码:

public class Draw extends JPanel implements ActionListener {


private int x = 100;
private int y = 100;
private double theta = Math.PI;

Rectangle rec = new Rectangle(x,y,25,25);

Timer timer = new Timer(25,this);

Draw(){
    setBackground(Color.black);
    timer.start();
}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;     
    g2d.setColor(Color.white);
    rec.x = 100;
    rec.y = 100;
    g2d.rotate(theta);
    g2d.draw(rec);
    g2d.fill(rec);

}

public void actionPerformed(ActionEvent e) {
    x = (int) (x + (Math.cos(theta))*1);
    y = (int) (y + (Math.sin(theta))*1);
    theta = theta - (5*Math.PI/180);
    repaint();
}

【问题讨论】:

  • 平移使得矩形以 (0,0) 为中心。旋转。翻译回来。

标签: java swing rotation awt java-2d


【解决方案1】:

常用两种方法之一:

  • 围绕Shape的中心(xy)旋转图形上下文,如图here

    rotate(double theta, double x, double y)
    
  • 平移到原点,旋转平移回来,如图here

    g2d.translate(this.getWidth() / 2, this.getHeight() / 2);
    g2d.rotate(theta);
    g2d.translate(-image.getWidth(null) / 2, -image.getHeight(null) / 2);
    

注意第二个例子中明显的反向串联顺序。

附录:仔细查看您的示例,以下更改围绕面板中心旋转 Rectangle

g2d.rotate(theta, getWidth() / 2, getHeight() / 2);

另外,使用@Override 注释,并为您的面板提供合理的首选尺寸:

@Override
public Dimension getPreferredSize() {
    return new Dimension(640, 480);
}

【讨论】:

  • 感谢您的回答,您所说的第一种方法就是我需要的方法。我没有意识到rotate方法有参数来定位它的坐标,所以我把矩形的位置作为参数,效果很好。再次感谢。
  • +1 非常好。 @user1914793 另见example,它使用AffineTransform#rotate(..)AffineTransform#createTransformedShape():
【解决方案2】:

使用仿射变换旋转矩形并将其转换为旋转多项式。检查下面的代码:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.white);
    /* rotate rectnagle around rec.x and rec.y */
    AffineTransform at = AffineTransform.getRotateInstance(theta, 
        rec.x, rec.y);
    /* create the plunomial */
    Polygon p = new Polygon();
    /* path interator of the affine transformed polynomial */
    PathIterator i = rec.getPathIterator(at);
    while (!i.isDone()) {
        double[] points = new double[2];
        i.currentSegment(points);
        p.addPoint((int) points[0], (int) points[1]);

        i.next();
    }
    g2d.fill(p);
}

【讨论】:

  • 不需要迭代Shape的路径;改用createTransformedShape(),如图here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 2011-05-07
相关资源
最近更新 更多