我试图在 Canvas 上旋转 PNG 图像,旋转后图像的质量变得非常糟糕。最初,PNG 是透明背景上的箭头。旋转后无法看出它是箭头。
我使用以下代码:
Transform oldTransform = new Transform(
Display.getCurrent());
gc.getTransform(oldTransform);
Transform transform = new Transform(Display.getCurrent());
transform.translate(xm + imageBounds.width / 2, ym + imageBounds.height / 2);
transform.rotate(179);
transform.translate(-xm - imageBounds.width / 2, -ym - imageBounds.height / 2);
gc.setTransform(transform);
gc.drawImage(image, xm, ym);
gc.setTransform(oldTransform);
transform.dispose();
提前谢谢您。
最佳答案
您可以水平和垂直翻转图像(无需任何像素转换),而不是将图像旋转 180 度:
private BufferedImage flipH(BufferedImage src) {
int w = src.getWidth();
int h = src.getHeight();
BufferedImage dst = new BufferedImage(w, h, src.getType());
Graphics2D g = dst.createGraphics();
g.drawImage(src,
0, // x of first corner (destination)
0, // y of first corner (destination)
w, // x of second corner (destination)
h, // y of second corner (destination)
w, // x of first corner (source)
0, // y of first corner (source)
0, // x of second corner (source)
h, // y of second corner (source)
null);
g.dispose();
return dst;
}
private BufferedImage flipV(BufferedImage src) {
int w = src.getWidth();
int h = src.getHeight();
BufferedImage dst = new BufferedImage(w, h, src.getType());
Graphics2D g = dst.createGraphics();
g.drawImage(src, 0, 0, w, h, 0, h, w, 0, null);
g.dispose();
return dst;
}
...
BufferedImage flipped = flipH(flipV(ImageIO.read(new File("test.png"))));
ImageIcon icon = new ImageIcon(flipped);
...
编辑:或者更好的是,在单个操作中水平和垂直翻转(与旋转 180 度相同):
g.drawImage(src, 0, 0, w, h, w, h, 0, 0, null);
Edit2:还有 SWT 特定的图像旋转/翻转示例,无需 Transform too .
关于java - 无法使用 swt Transform 旋转透明图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6227949/