我正在尝试轮换缓冲的Image
并使用Image
方法返回缓冲的getImage()
(旋转图像)。图像旋转正在发生,但保存图像时保存图像而不旋转图像。
初始化:
private BufferedImage transparentImage;
PaintComponent:
AffineTransform at = new AffineTransform();
at.rotate(Math.toRadians(RotationOfImage.value));
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(transparentImage, at, null);
repaint();
返回旋转缓冲图像的方法。
public BufferedImage getImage(){
return transparentImage;
}
答案 0 :(得分:2)
基本上,您正在旋转组件的Graphics
上下文并将图像绘制到该组件上,这对原始图像没有任何影响。
相反,你应该旋转图像和绘画,例如......
public BufferedImage rotateImage() {
double rads = Math.toRadians(RotationOfImage.value);
double sin = Math.abs(Math.sin(rads));
double cos = Math.abs(Math.cos(rads));
int w = transparentImage.getWidth();
int h = transparentImage.getHeight();
int newWidth = (int) Math.floor(w * cos + h * sin);
int newHeight = (int) Math.floor(h * cos + w * sin);
BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = rotated.createGraphics();
AffineTransform at = new AffineTransform();
at.translate((newWidth - w) / 2, (newHeight - h) / 2);
at.rotate(Math.toRadians(RotationOfImage.value), w / 2, h / 2);
g2d.setTransform(at);
g2d.drawImage(transparentImage, 0, 0, this);
g2d.setColor(Color.RED);
g2d.drawRect(0, 0, newWidth - 1, newHeight - 1);
g2d.dispose();
}
然后你可以把它画成像...这样的东西。
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
BufferedImage rotated = rotateImage();
int x = (getWidth() - rotated.getWidth()) / 2;
int y = (getHeight() - rotated.getHeight()) / 2;
g2d.drawImage(rotated, x, y, this);
g2d.dispose();
}
现在,您可以对此进行优化,因此您只需在角度发生变化时生成图像的旋转版本,但我会将其留给您
ps-我没有对此进行测试,但它基于此question