Fade in/out effect too slow

Hi!

I’m trying to do a fade in/out effect between two images using the following code:


public void render(Graphics g, Image imageFrom, Image imageTo, int width, int height) {

      Image buffer=gc.createCompatibleVolatileImage(width,height);

      Graphics2D g2 = (Graphics2D)buffer.getGraphics();  
                                
      int counter=0;
      while (counter<90) {
            counter=counter+2;
            double alphaScalar = Math.sin(Math.toRadians(counter)); 
                  g2.setComposite(AlphaComposite.SrcOver);
            g2.drawImage(imageFrom, 0, 0, null);  
                  g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float)alphaScalar));
            g2.drawImage(imageTo, 0, 0, null);
            g.drawImage(buffer, 0, 0, null);
            try {
                  Thread.sleep(1);  
            }
            catch(InterruptedException ex){}
      }                                                                    
            
      g.dispose();
      g2.dispose();
      buffer.flush();
}

The problem is that it’s too slow and jerky. I need a smoother transition.

Before you ask me, I’ve put a “Thread.sleep(1)” line to allow another thread playing a background music to breath.

Thanks in advance

if you have a good timer that can tell you how much time has elapsed between drawing calls, you can scale “counter” by the elapsed time. Moving by 2 every time does not compensate at all for any differences in time that loops might take.