我正在用Java创建一个小游戏,我有一个旋转的图像。
正如你在下面的两张图片中所看到的,有一艘巨型船在游戏中缓慢旋转,但当它到达某一点时会被切断(由于它自己的小BufferedImage)。
继承我的渲染代码:
public void drawImageRotated(BufferedImage img, double x, double y, double scale, double angle) {
x -= xScroll;
y -= yScroll;
BufferedImage image = new BufferedImage((int)(img.getWidth() * 1.5D), (int)(img.getHeight() * 1.5D), 2);
Graphics2D g = (Graphics2D)image.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.rotate(Math.toRadians(angle), image.getWidth() / 2, image.getHeight() / 2);
g.drawImage(img, image.getWidth() / 2 - img.getWidth() / 2, image.getHeight() / 2 - image.getHeight() / 2, null);
g2d.drawImage(image, (int)(x-image.getWidth()*scale/2), (int)(y-image.getHeight()*scale/2), (int)(image.getWidth()*scale), (int)(image.getHeight()*scale), null);
g.dispose();
}
回到眼前的问题,如何在旋转过程中计算出图像的最大x和y尺寸,这样我可以用我的缓冲图像尺寸进行补偿?
答案 0 :(得分:1)
如何在旋转过程中计算出图像的最大x和y尺寸,以便我可以用我的缓冲图像尺寸进行补偿?
double sin = Math.abs(Math.sin(angle));
double cos = Math.abs(Math.cos(angle));
int w = image.getWidth();
int h = image.getHeight();
int neww = (int)Math.floor(w*cos+h*sin);
int newh = (int)Math.floor(h*cos+w*sin);
以上代码取自此示例:Java(SWING) working with Rotation
答案 1 :(得分:1)
如果您的基本矩形图像围绕其中心旋转,则旋转期间的最大宽度和高度将是图像矩形的对角线水平或垂直时。这个对角线距离可以用毕达哥拉斯定理计算,并用于BufferedImage
的宽度和高度。
int size = (int) Math.sqrt((img.getWidth() * img.getWidth()) + (img.getHeight() * img.getHeight()));
BufferedImage image = new BufferedImage(size, size, 2);
// The rest of your code as before
答案 2 :(得分:0)
另一种方法是旋转实际的Graphics
对象,绘制图像并恢复旋转:
AffineTransform old = g2d.getTransform();
g2d.rotate(Math.toRadians(angle), x + image.getWidth() / 2, y + image.getWidth() / 2);
g2d.drawImage(image, x, y, null);
g2d.setTransform(old);
答案 3 :(得分:0)
我们假设width
是原始图像的宽度,height
是原始高度,angle
是旋转角度值,以弧度为单位。
根据我的计算,旋转图像的大小如下:
rotatedWidth = Math.cos(angle) * width + Math.sin(angle) * height;
rotatedHeight = Math.sin(angle) * width + Math.cos(angle) * height;
您可能还需要查看this主题,因为它可能有所帮助。