Why gif animation doesn't animate when using it in paintComponent()?

纵然是瞬间 提交于 2019-11-28 13:32:23

The reason is that the standard Java ImageIO API only loads the first image of the gif. How to fix? Google for a Gif Loader for Java, which loads every image of the gif. Then you have to paint the right image at the right time. An alternative way would be to have different png files representing each time one frame of the animation.

Update: Well... Actually, after doing some research, it looks like the way you did it actually loads all the frames of the animated gif. The reason for it is that the ImageIcon's method getImage() always returns the first image.

To fix it, you can try this (I'm not sure if it will work...)

Instead of using Grahpics.drawImage(), use ImageIcon.paintIcon(). Like this:

imageIcon.paintIcon(this, g2d, getWidth() / 2 - imageIcon.getIconWidth() / 2, getHeight() / 2);

Image observer will take care of it. You should just pas the observer to the g2d.drawImage(); as below.

g2d.drawImage(imageIcon.getImage(), getWidth() / 2, getHeight() / 2, this);

In my case 'this' refer to CirclePanel which extends JPanel, it can be any thing for example if you are using gif as a icon for a button, you should use button as image observer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!