Java在中心旋转图像

4
我该如何使一张图片绕着其中心旋转?以下代码可实现图片旋转,但它仅在屏幕左上角旋转:
    AffineTransform oldtrans = new AffineTransform();
    AffineTransform trans = new AffineTransform();

    trans.setToIdentity();
    trans.rotate(Math.toRadians(angle));
    trans.translate(_x-(width/2), _y-(height/2));
    g.setTransform(trans);
    g.drawImage(this.getImage(), (int)_x, (int)_y, (int)width, (int)height, null);
    trans.setToIdentity();
    g.setTransform(oldtrans);

请帮帮我!!!

2个回答

9

您需要在rotate()调用中再添加两个参数:

affineTransform.rotate(Math.toRadians(angle), m_imageWidth/2, m_imageHeight/2); 

我忘了这个……这应该比我建议的单独翻译更快(但本质上是相同的)。代码也更少(+1)。 - Jaco Van Niekerk

4

您已经完成了一半的工作。您需要进行两次翻译,大致如下:

  1. 将图像翻译到其中心位置(translate(x-width/2, y-width/2))。
  2. 以弧度为单位旋转图像(就像您所做的那样)。
  3. 将图像翻译回其原始位置(translate(x+width/2, y+width/2))。

希望这对您有帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接