Scroll transition between two images

Hi!

I’m using the following code to render a left to right scroll transition between two images over a JPanel:


public void render(JPanel panel, Image imageFrom, Image imageTo) {

    Image buffer = gc.createCompatibleVolatileImage(panel.getWidth(), panel.getHeight()); 

    Graphics g = buffer.getGraphics();
    Graphics g2 = panel.getGraphics();  
                                
    for (int x=0; x<=panel.getWidth(); x+=10) {
      g.drawImage(imageFrom, x, 0, panel);  
      g.drawImage(imageTo, x-panel.getWidth(), 0, panel);
      g2.drawImage(buffer, 0, 0, panel);  
      try {
            Thread.sleep(20);  
      }
        catch(InterruptedException ex){}
    }       

    g.dispose();
    g2.dispose();
    buffer.flush();
                                                                            
}

As you can see I render out of the bounds of the screen many times during the transition. I suppose I can improve the performance not drawing the offscreen parts. How can I do it ? Is easy ? Can anyone help me, please ?

Thanks in advance

You don’t need an intermediate image buffer. draw directly to the panel and use a clip (g.clipRect(…)) to mask out where you don’t want the image to draw.

Make sure that imageFrom and imageTo is images that are “managed”. See Chet Haase’s tutorials at javadeskop.org if you are unsure about how to get them. Makes a big difference.

Cheers,
Mikael Grev

I’m not using a BufferStrategy. If I don’t use an intermediate buffer won’t the screen flicker ?

Swing components are double buffered by default so I don’t think so. Maybe if the drawing of the images would take very long time, then, maybe. I would definitely go without an immediate image. Give it a try anyway. If you have an accelerated image, drawing it is almost instantaneous.

I think the call to createCompatibleVolatileImage() takes a long time so I would stay away from making a new one all the time. If you must use that intermediate image, you should (probably) save the volitile image between the renderings. I also think a regular BufferedImage (that is accelerated) would do. Volitile images need more manual house keeping since they can lose their contents at any time.

Chet’s Image tutorials is a must. (they are short). :slight_smile:

Cheers,
Mikael

Thank you very much. I’m glad there are people out there helping newbies like me. :smiley: