Replace only the corners of a rotated image with a different color

103 views Asked by At

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.)

2

There are 2 answers

0
camickr On BEST ANSWER

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(...);
1
ebeneditos On

If I understood correctly, you have the following rotation:

enter image description here

The green cells are the original image rotated, while the white ones the area you want to delete. From the rotation and the degrees given, you can know the coordinates of the red cells and thus, delete cells that meet the conditions:

(x_coord <= x1 and y_coord > x_coord * y1 / x1) /* Top Left */ or
(x_coord >= x2 and y_coord > x_coord * y2 / x2) /* Top Right */ or
(x_coord >= x3 and y_coord < x_coord * y3 / x3) /* Bottom Right */ or 
(x_coord <= x4 and y_coord < x_coord * y4 / x4) /* Bottom Left */

Hope this helped!