为什么在paintComponent() 中使用gif 动画时没有动画?
我正在使用 paintComponent()
在 JPanel
的背景上绘制 gif 动画图像.它显示了 gif 但没有动画.我使用 java 1.5,我知道我可以使用带有图标的标签.
I'm using paintComponent()
to paint a gif animated image at the backgound of JPanel
.
It shows up the gif but doesn't animate.
I use java 1.5 and i know that i can use label with icon.
有没有人知道为什么以及如何解决它?
private static class CirclePanel extends JPanel {
ImageIcon imageIcon = new ImageIcon(BarcodeModel.class.getResource("verify.gif"));
Point point = f.getLocation();
protected void paintComponent(Graphics g) {
Graphics gc = g.create();
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f));
g2d.setColor(Color.BLUE);
g2d.drawImage(imageIcon.getImage(), getWidth() / 2, getHeight() / 2, null);
g2d.drawRect(0, 0, getWidth(), getHeight());
g2d.setStroke(new BasicStroke(10f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER));
g2d.setFont(g.getFont().deriveFont(Font.BOLD | Font.ITALIC,15f));
g2d.drawString("Wait Please ...",getWidth()/2-imageIcon.getIconHeight()/3,getHeight()/2+imageIcon.getIconHeight()+15);
g2d.dispose();
}
这是 gif 图像.
This is the gif image.
只需将图像观察器添加到 g2d.drawImage() 方法.
Edited: just add image observer to the g2d.drawImage() method.
g2d.drawImage(imageIcon.getImage(), getWidth() / 2, getHeight() / 2, this);
原因是标准 Java ImageIO API 只加载 gif 的第一张图像.怎么修?谷歌为 Java 寻找一个 Gif 加载器,它加载 gif 的每个图像.然后你必须在正确的时间绘制正确的图像.另一种方法是让不同的 png 文件代表动画的每一帧.
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.
更新:嗯...实际上,经过一些研究后,看起来您这样做的方式实际上加载了动画 gif 的所有帧.原因是 ImageIcon 的方法 getImage()
总是返回第一张图像.
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...)
不要使用 Grahpics.drawImage()
,而是使用 ImageIcon.paintIcon()
.像这样:
Instead of using Grahpics.drawImage()
, use ImageIcon.paintIcon()
. Like this:
imageIcon.paintIcon(this, g2d, getWidth() / 2 - imageIcon.getIconWidth() / 2, getHeight() / 2);