【问题标题】:Image not drawn to a fixed position when rotating with AffineTransform使用 AffineTransform 旋转时图像未绘制到固定位置
【发布时间】:2012-01-03 15:34:24
【问题描述】:

我在使用 Graphcis2D 和 AffineTransform 将图像旋转到固定位置时遇到问题。

这个想法是根据身体的旋转来旋转图像。

旋转发生正确,因为图像的旋转角度与身体旋转的角度相匹配。然而,随着旋转的发生,图像不会被绘制到与身体应该被绘制的相同位置。绘制图片的方法代码如下:

public void paintPicture(Graphics g, Body body) {

    Graphics2D g2 = (Graphics2D) g;

    Vector2f[] vertices = ((Box) body.getShape()).getPoints(body.getPosition(), body.getRotation());

    Vector2f topLeftCorner = vertices[0];

    AffineTransform oldTransform = g2.getTransform();

    AffineTransform at = new AffineTransform();

    at.rotate(body.getRotation());

    g2.setTransform(at);

    g2.drawImage(this.img, (int) topLeftCorner.x, (int) topLeftCorner.y, null);

    g2.setTransform(oldTransform);
}

任何想法可能导致图像移动而不是根据坐标(topLeftCorner.x,topLeftCorner.y)绘制它?

【问题讨论】:

    标签: java graphics affinetransform


    【解决方案1】:

    您需要首先平移您的对象,使锚点(您希望它围绕其旋转的点)位于原点,执行您的旋转,然后将其平移回来。因此,如果您想围绕点 (50, 75) 旋转,您可以执行以下操作:

    at.translate (-50, -75);
    at.rotate (body.getRotation());
    at.translate (50, 75);
    

    我假设您的 AffineTransform 类可以累积转换。如果没有,您将需要 3 种不同的转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      相关资源
      最近更新 更多