Java2D-如何旋转图像并保存结果
我正在做一个游戏,其中一些物体旋转以面对他们射击的目标。在拍摄之间有一个延迟,我希望物体保持朝向它所在的位置,直到它再次拍摄。我知道如何加载图像,我知道如何使用仿射变换旋转图像。但有了这个,我需要在每次绘制对象时计算旋转 因此,我的问题是如何旋转图像并将结果保存到新图像中以显示 如何旋转图像并将结果保存到将显示的新图像中?Java2D-如何旋转图像并保存结果,java,image,rotation,Java,Image,Rotation,我正在做一个游戏,其中一些物体旋转以面对他们射击的目标。在拍摄之间有一个延迟,我希望物体保持朝向它所在的位置,直到它再次拍摄。我知道如何加载图像,我知道如何使用仿射变换旋转图像。但有了这个,我需要在每次绘制对象时计算旋转 因此,我的问题是如何旋转图像并将结果保存到新图像中以显示 如何旋转图像并将结果保存到将显示的新图像中? 创建一个新的buffereImage。获取一个图形对象(通过。将旋转的图像绘制到此缓冲图像上,并根据其旋转将图像保存在数组或地图中(以便在需要时轻松查找)。尝试以下方法克隆图
创建一个新的
buffereImage
。获取一个图形
对象(通过。将旋转的图像绘制到此缓冲图像上,并根据其旋转将图像保存在数组或地图中(以便在需要时轻松查找)。尝试以下方法克隆图像:
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);
旁白:忽略我之前的回答,我误读了这个问题。对不起
Affline变换仅适用于完美正方形
用于拍摄任何矩形图像并正确旋转它
这样,它会选择一个中心点,该中心点的长度为较大长度的一半,并且
使库认为图像是一个完美的正方形,然后
进行旋转并告诉库在何处找到正确的顶部
左点。每个方向的特殊情况发生在
不存在的额外图像位于左侧或顶部
图像正在旋转。在这两种情况下,点都由
长边和短边的差异,以获得点
正确的图像左上角。注意:x轴和y轴
与图像一起旋转,以便始终在宽度>高度的位置进行调整
发生在y轴上,调整的高度>宽度
发生在x轴上
感谢您的快速响应。我应该对所有360度进行旋转吗?图像非常小,因此每2或5度旋转一个图像也可以吗?如果我需要,我会将其设置为编译时间常量。类似于
NUM_ROTATIONS
并创建BufferedImage[NUM_ROTATIONS]
按住精灵,并通过i*360.0/NUM\u旋转旋转每个精灵。然后您可以轻松尝试不同的旋转。很快您就可以:-)
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);
}