When I try to use a GIF in a JLabel
either resized or normal, it smears and produces an odd effect:
The GIF I'm using:
Layout of the JPanel
it is attached to is null
, and images that are accessed are part of a jar file.
Here's the code for creating and adding the label:
public JLabel j_Anim(String path, int width, int height, int xpos, int ypos, boolean applyscaling) throws Exception {
Image finimage;
if (!applyscaling) {
finimage = new ImageIcon(Main.class.getResource(path)).getImage();
} else {
finimage = (new ImageIcon(Main.class.getResource(path)).getImage()).getScaledInstance(width, height, Image.SCALE_DEFAULT);
}
JLabel im = new JLabel(new ImageIcon(finimage));
group.panel.add(im);
im.setBounds(xpos, ypos, width, height);
return im;
}
I'm fairly new to java, so any help would be greatly appreciated!
EDIT: Minimal Reproducable Example:
import javax.swing.*;
import java.awt.*;
class Main extends JFrame {
public static void main(String[] args) {
Main ma = new Main();
}
Main() {
JPanel p = new JPanel();
this.setSize(300, 300);
this.add(p);
JLabel im = new JLabel(new ImageIcon(this.getClass().getResource("img/walk.gif")));
p.add(im);
this.setVisible(true);
this.pack();
}
}
EDIT 2: This behaviour is only happening with gifs that have transparent backgrounds, standard solid-background gifs work fine. However, the issue is still unresolved because I need to use a gif with a transparent background. Thanks for the help so far!
EDIT 3: The issue was solved by changing the gif's disposal method to background. I used this cmd script with imagemagick to generate a custom gif with the specified disposal method from a spritesheet:
set WIDE=50
set HIGH=75
set XCOORD=0
set YCOORD=0
set FRAMES=8
convert spritesheet.png ^
-set option:distort:viewport %[fx:%FRAMES%*%WIDE%]x%HIGH% ^
-set option:slider %[fx:%YCOORD%*(w/%WIDE%)+%XCOORD%] ^
-crop %WIDE%x%HIGH% +append +repage ^
-distort affine "%[slider],0 0,0" ^
-crop %WIDE%x%HIGH% +repage ^
-set delay 10 -loop 0 -set dispose Background result.gif
pause
exit