How to fade-in / fade-out a Java Graphics?

11,545

Solution 1

You could try painting the image over and over again but with a different opacity (alpha) value. Start from 0 (completely transparent) and gradually increase to 1 (opaque) in order to produce a fade-in effect. Here is some test code which might help:

float alpha = 0.0f;

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;

    //set the opacity
    g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, alpha));
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

    //do the drawing here
    g2d.drawLine(10, 10, 110, 110);
    g2d.drawRect(10, 10, 100, 100);

    //increase the opacity and repaint
    alpha += 0.05f;
    if (alpha >= 1.0f) {
        alpha = 1.0f;
    } else {
        repaint();
    }

    //sleep for a bit
    try {
        Thread.sleep(200);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }
}

Solution 2

Have a look at the AlphaComposite class for the transparency, and the Swing based Timer class for timing.

The Java 2D API Sample Programs has demos. under the Composite heading that show how to tie them together.

Solution 3

Take a look at the Java Timing Framework.

Share:
11,545
Michael Mao
Author by

Michael Mao

Hi all. I now work at IBM as Associative Support Software Engineer in Sydney. I am always interested in developing my programming skills after work (technical support for Cognos). So maybe I am not a good programmer, but I am sure a good questioner :)

Updated on June 04, 2022

Comments

  • Michael Mao
    Michael Mao almost 2 years

    Say if I have a Java Graphics object, and I want to draw a line or a rectangle on it. When I issue the command to draw, it appears on screen immediately. I just wonder how could I make this progress as a fade-in / fade-out effect, same as what you can achieve in Javascript.

    Any thoughts?

    Many thanks for the help and suggestions in advance!

  • wchargin
    wchargin about 11 years
    Pardon me if I'm missing something, but... are you sleeping on the Event Dispatch Thread??