繁体   English   中英

Java2D - 如何旋转图像并保存结果

[英]Java2D - How to rotate an image and save the result

我正在制作一个游戏,其中一些物体旋转以面对它们正在拍摄的东西。 拍摄之间有延迟,我希望 object 一直面向它所在的位置,直到再次拍摄。 我知道如何加载图像,也知道如何使用 AffineTransform 旋转它们。 但是有了这个,我需要在每次绘制 object 时计算旋转。

所以我的问题是如何旋转图像并将结果保存到将显示的新图像中?

如何旋转图像并将结果保存到将要显示的新图像中?

创建一个新的BufferedImage 获取Graphics object(通过BufferedImage.getGraphics() 。将旋转后的图像绘制到此缓冲图像上,并根据其旋转将图像保存在数组或 map 中(以便在需要时轻松查找) )。

仿射变换仅适用于完美正方形。 以下代码用于获取任何矩形图像并正确旋转它。 为此,它会选择一个中心点,该中心点是更大长度的一半,并欺骗库认为图像是一个完美的正方形,然后它进行旋转并告诉库在哪里可以找到正确的左上角点。 当不存在的额外图像位于被旋转图像的左侧或顶部时,每个方向的特殊情况都会发生。 在这两种情况下,通过长边和短边的差异来调整点,以获得图像正确左上角的点。 注意:x 和 y 轴也随着图像旋转,因此宽度 > 高度的调整总是发生在 y 轴上,而高度 > 宽度的调整发生在 x 轴上。

private BufferedImage rotate(BufferedImage image, double _theta, int _thetaInDegrees) {

    AffineTransform xform = new AffineTransform();

    if (image.getWidth() > image.getHeight()) {
        xform.setToTranslation(0.5 * image.getWidth(), 0.5 * image.getWidth());
        xform.rotate(_theta);

        int diff = image.getWidth() - image.getHeight();

        switch (_thetaInDegrees) {
            case 90:
                xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth() + diff);
                break;
            case 180:
                xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth() + diff);
                break;
            default:
                xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth());
                break;
        }
    } else if (image.getHeight() > image.getWidth()) {
        xform.setToTranslation(0.5 * image.getHeight(), 0.5 * image.getHeight());
        xform.rotate(_theta);

        int diff = image.getHeight() - image.getWidth();

        switch (_thetaInDegrees) {
            case 180:
                xform.translate(-0.5 * image.getHeight() + diff, -0.5 * image.getHeight());
                break;
            case 270:
                xform.translate(-0.5 * image.getHeight() + diff, -0.5 * image.getHeight());
                break;
            default:
                xform.translate(-0.5 * image.getHeight(), -0.5 * image.getHeight());
                break;
        }
    } else {
        xform.setToTranslation(0.5 * image.getWidth(), 0.5 * image.getHeight());
        xform.rotate(_theta);
        xform.translate(-0.5 * image.getHeight(), -0.5 * image.getWidth());
    }

    AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_BILINEAR);

    return op.filter(image, null);
}

尝试这样的事情来克隆图像:

BufferedImage source = new BufferedImage(50, 10, BufferedImage.TYPE_4BYTE_ABGR); 

BufferedImage target = new BufferedImage(50, 10, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D tg = target.createGraphics();

AffineTransform at = new AffineTransform();
at.rotate(2);

tg.drawImage(source, at, null);

PS:忽略我之前的回答,我误读了这个问题。 对不起。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM