无法使用swt Transform旋转透明图像

时间:2011-06-03 13:50:49

标签: java image swt rotation

我正在尝试在画布上旋转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();

提前谢谢。

1 个答案:

答案 0 :(得分:3)

不是将图像旋转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:除了转换 too之外,还有特定于SWT的图像旋转/翻转示例。