Search code examples
javagraphicstransparencyfadealpha

Fade between transparency and a color in Graphics


I am trying to accomplish something like shown below (fade between white and transparency) without adding a picture.

enter image description here


Solution

  • If you're using a BufferedImage, the alpha channel is simply the most significant byte of the result of getRGB():

    int alpha = (image.getRGB(x, y) & 0xFF000000) >> 24;
    

    So, you can change the alpha whilst preserving the color using:

    int original = image.getRGB(x, y);
    int newColor = (original & 0x00FFFFFF) | (alpha << 24);
    image.setRGB(x, y, newColor);
    

    (assuming 0 <= alpha <= 255).