0

Currently in my code I have a BufferedImage drawn like:

Graphics2D g2d = (Graphics2D) g;
g2d.transform(at); //at is an AffineTransform that just rotates the .gif
g2d.drawImage(sharkie, xCenter-5*radius, yCenter-3*radius, 10*radius, 6*radius, null);

I already have it fully functioning as a BufferedImage, but as expected it shows only the first frame. I was wondering if anyone knew of a way that is analogous to BufferedImage that works for animated gifs. I can't seem to get swing to work with the technique of adding it to a JButton. I also cannot figure out if there is a viable ImageObserver that would animate the .gif in the drawImage() call.

I am willing to try anything, but I am most interested in the possibility of making the draw call work with an ImageObserver as that would be only a small change.

Thanks all!

4

1 回答 1

1

“我已经将它完全用作 BufferedImage,但正如预期的那样,它只显示第一帧”

尝试使用 读取图像时会发生这种情况ImageIO.read(...)。如果你用 阅读它new ImageIcon(...).getImage(),你会得到 gif 动画。见这里

“我也不知道是否有一个可行的 ImageObserver 可以在 drawImage() 调用中为 .gif 设置动画。”

ImageObserver是您正在绘制的组件。因此drawImage(..., null),您应该使用而不是使用drawImage(..., this)

“我愿意尝试任何事情,但我最感兴趣的是让绘图调用与 ImageObserver 一起工作的可能性,因为这只是一个很小的改变。”

结合以上两点,你就得到了答案。


给这个代码一个测试运行。取自此答案的 gif 图像

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestGif {

    public TestGif() {
        JFrame frame = new JFrame();
        frame.add(new GifPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public class GifPanel extends JPanel {
        Image image;
        {
            try {
                image = new ImageIcon(new URL("http://i.stack.imgur.com/lKfdp.gif")).getImage();
            } catch (MalformedURLException ex) {
                Logger.getLogger(TestGif.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, this);
        }
        @Override
        public Dimension getPreferredSize() {
            return image == null ? new Dimension(200, 200) 
                    : new Dimension(image.getWidth(this), image.getHeight(this));
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestGif();
            }
        });
    }
}
于 2014-03-20T18:38:19.477 回答