使用 AffineTransform 旋转时图像未绘制到固定位置

发布于 2024-12-23 17:20:10 字数 778 浏览 2 评论 0原文

我在使用 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)绘制图像?

I have a problem with rotating image in a fixed position with Graphcis2D and AffineTransform.

The idea is to rotate an image according to body's rotation.

The rotation is happening correctly as the rotation angle of the image matches the angle of the body's rotation. However, as the rotation takes place, the image is not drawn to the same position as the body should be drawn. The code of the method painting the picture is the following:

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

Any ideas what might cause the movement of the image instead of drawing it according to the coordinates (topLeftCorner.x, topLeftCorner.y)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜是你 2024-12-30 17:20:10

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

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

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

You need to first translate you object so the anchor point (the point around which you want it to rotate) is at the origin, perform your rotation, then translate it back. So if you want to rotate around the point (50, 75), you'd do the following:

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

I'm assuming that your AffineTransform class can accumulate transformations. If not, you'll need 3 different transforms.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文