1

I am using a GIF with a transparent background as a sprite for a game I am making as it is easier than manually animating each frame of the idle animation, especially since that is the only animation I will be using for a while. My issue is that each frame of the GIF is rendered, but is still visible once the next appears. For example, when the sprite's wing lowers, the previous frame is still visible behind the newest frame with the wing higher up. I dont think that this an issue with the GIF, since it looks just fine outside of my program, but here it is anyways: Sprite

I've tried reworking the code, trying to use clearRect(); and g2.dispose(); but nothing seemed to work. Here is my code for the graphics:

public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        // drawing food and powerups
        g2.clearRect(px, py, pw, ph);
        
        Color transGray = new Color(126, 126, 126, 50);
        Color transGreen = new Color(0, 255, 0, 150);
        Image icon = new ImageIcon(getClass().getResource("/resources/Anti_Virus_Sprite.gif")).getImage();
        g2.drawImage(icon,px, py, pw, ph, null);
        g2.drawRect(px, py, pw, ph);
        
        //g2.dispose();

    }


Everything else works fine I should also add, only this GIF is doing it, no issues with drawRect();

I did find that with a different GIF, one completely unrelated for a different game, it didnt seem to had the same issue, but that GIF didn't move much so it could have just been difficult to notice. A side note, some of the GIFs I use flicker weirdly sometimes, but only in my programs.

  • You need to change the `disposalMethod` for [example](https://stackoverflow.com/questions/20318146/java-gif-creator-needs-tweaking/20318211#20318211); [example](https://stackoverflow.com/questions/26330550/java-gif-animation-not-repainting-correctly/26331052#26331052); [example](https://stackoverflow.com/questions/36671767/java-swing-gif-partly-transparent-when-its-not-supposed-to-be/36683021#36683021); [example](https://stackoverflow.com/questions/18117283/mirroring-animated-gif-on-load-in-java-imageicon/18117326#18117326) – MadProgrammer Apr 10 '23 at 06:34
  • [example](https://stackoverflow.com/questions/36682135/java-animated-gifs-go-automatically-partially-transparent/36682907#36682907) – MadProgrammer Apr 10 '23 at 06:35
  • Don't load the image in the `paintComponent` method and pass `this` as the `ImageObserver` to the `drawImage` method – MadProgrammer Apr 10 '23 at 06:39

0 Answers0