Search code examples
javaswingjframegifanimated-gif

.getScaledInstance working with animated GIFs


I have scaled images easily with the .getScaledInstance when importing them like so:

player_sprite = a_1.getImage().getScaledInstance(150, 150, 100);

But the same cannot be said about scaling animated GIFs as when I do the same method of scaling a GIF it causes issues when displaying it. When using g.drawImage it only draws the first frame then disappears.

Here is the full code for importing the GIF that I use and below will be an example of how I display the animated GIF onto the JFrame:

Importing it:

    ImageIcon a_1 = new ImageIcon(FrontHand.class.getResource("/Sprites/character_move_down.gif"));
    move_player_down = a_1.getImage().getScaledInstance(100, 100, 100);

Displaying it:

    g.drawImage(move_player_down, 100, 100, this);

Is there another simple method I could use for increasing the size of the animated GIF or is there a simple fix for this issue.


Solution

  • I have found a solution while going into scalr, I ended not with scalr but instead found a comment on a scalr thread which using .getscaledinstance is changing the size and then printing with paintIcon and not drawImage like so:

    Change in size:

    ImageIcon a_1 = new ImageIcon(FrontHand.class.getResource("/Sprites/character_move_down.gif"));
    a_1.setImage(a_1.getImage().getScaledInstance(150, 150, Image.SCALE_DEFAULT));
    move_player_down = a_1;
    

    Painting the icon:

    move_player_down.paintIcon(this, g, 100, 100);
    

    It works like a charm and does not require me to change all my previous code to work around it :)