2013-01-01 113 views
4

我想在JPanel中绘制一个矩形,它将翻译并旋转自身以模仿汽车的运动。我已经能够使矩形平移并旋转,但它围绕(0,0)的原点旋转。我非常高兴能够让矩形移动和旋转,因为我对Java GUI非常陌生,但我似乎无法得到如何让矩形围绕自身旋转,因为我对它进行了更多尝试,并且何时我初始化矩形并将其旋转45度,它的位置发生了变化,我将假设它是从旋转方法附加的变换矩阵。Java GUI旋转和矩形的翻译

我通过网站检查了如何解决这个问题,但是我只找到了如何旋转矩形,而不是如何旋转和移动像模拟汽车的运动。我会假设它是关于它的变换矩阵,但我只是在猜测。所以我的问题是,我将如何能够让矩形能够旋转和移动,而不是针对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(); 
} 
+3

翻译,使得该矩形为中心(0,0)。旋转。翻过来。 – ApproachingDarknessFish

回答

6

之一两种方法是常用的:

  • 旋转图形上下文围绕Shape的中心(Xÿ),如图所示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); 
} 
+1

感谢您的回答,您说的第一个方法就是我需要的方法。我没有意识到,旋转方法有参数来定位它的坐标,所以我把矩形的位置作为参数,它工作得很好。再次感谢。 –

+1

+1非常好。 @ user1914793另请参阅此[示例](http://stackoverflow.com/questions/13519449/rotate-rectangle-and-move-it-in-sin-wave-help-using-graphics2d/13519588#13519588)它使用' AffineTransform#rotate(..)'和'AffineTransform#createTransformedShape():' –

1

使用仿射变换,旋转矩形,并把它转换成旋转的多项式。检查以下的代码:

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); 
} 
+0

没有必要迭代“形状”的路径;改为使用'createTransformedShape()',如[here](http://stackoverflow.com/a/5594424/230513)所示。 – trashgod

+0

@trashgod感谢您指出。 – Shivam