I am currently making a game that requires the rotating of an image. In order to rotate it, I am using the following code.
public ManipulableImage rotate(double degrees){
BufferedImage rotatedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = rotatedImage.createGraphics();
g.rotate(Math.toRadians(degrees), image.getWidth()/2, image.getHeight()/2);
/*
ManipulableImage is a custom class that makes it easier to manipulate
an image code wise.
*/
g.drawImage(image, 0, 0, null);
return new ManipulableImage(rotatedImage, true).replace(0, -1);
}
The code does rotate the image, but it leaves the corners black which should be transparent. My renderer recognizes the rgb value -1 as the transparent value, and doesn't change a pixel when that value is present. So, I would like to change the rgb values of the corners from 0 (black) to -1 (transparent).
The only problem is, I can't simply iterate through the image and replace the black pixels because there are other pixels in the original image that are black. So my question is, how do I replace only the black pixels created by the rotation.
(Sorry I couldn't provide examples of the image, I'm not sure how to screenshot with this computer.)
The graphics object has no context to color these new pixels, so it simply colors them black.
BufferedImage rotatedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
You should be using the following so the BufferedImage
supports transparency:
BufferedImage.TYPE_INT_ARGB
Then in the painting code you can use:
g.setColor( new Color(0, 0, 0, 0) );
g.fillRect(0, 0, image.getWidth(), image.getHeight());
g.rotate(...);
g.drawImage(...);