I'm trying to rotate a PNG image on a canvas and the quality of the image becomes very bad after rotation. Initially the PNG is an arrow on a transparent background. After rotation it is impossible to tell that it开发者_运维知识库 is an arrow.
I use following code:
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();
Thank you in advance.
Instead of rotating the image 180 degrees, you could flip it horizontally and vertically (without any pixel transformation):
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);
...
Edit: or even better, flip both horizontally and vertically in single op (same as rotating 180 degrees):
g.drawImage(src, 0, 0, w, h, w, h, 0, 0, null);
Edit2: There is also SWT-specific example of image rotation/flipping without Transform too.
精彩评论