我在做一个小游戏。这不是一个行动,而是一个难题,所以表现并不那么重要。 现在,我有主游戏区,一个背景图片。在某些情况下,我想在背景图像的一部分上绘制其他图像。 我的问题是,背景图像以及叠加的(一个或多个)背景图像都可以是GIF动画,具有未知数量的帧(基本上,用户选择)。Java:在其他动画gif上叠加/叠加动画gif
现在,我想要做的事情基本上是:绘制背景图像并将其设置为动画(如果它是gif),然后在其上绘制0-n个较小的动画gif,相对于背景图像的位置,像素坐标。 此外,它应该可调整大小,以便图像相应地缩放/移动。
如何最终结果可能类似于:http://i.stack.imgur.com/PxdDt.png(试想一下它的动画)
我已经找到了它一个解决方案,它的工作原理是设置布局管理器为null,使用绝对定位的JLabel与图标有他们的动画,使用一个作为背景,另一个添加到它的前景:
background.setSize(backgroundIcon.getIconWidth(), backgroundIcon.getIconHeight());
foreground.setSize(foregroundIcon.getIconWidth(), foregroundIcon.getIconHeight());
background.setLocation(0, 0);
foreground.setLocation(30, 30);
background.setLayout(null);
background.add(foreground);
frame.setLayout(null);
frame.add(background);
(以下全码)
设置布局管理器为NULL,因为我听说,有问题(特别,因为我想。想要 稍后在图像中添加一些文字,尽管我会在背景中使用另一个标签,而不是背景标签本身或其他东西),调整大小似乎不可能,因为我无法调整JLabels图像图标的大小(发现了一些解决方案,它将gif分割成每层一个bufferedImage,并在将它们重新放回到一起之前调整它们的大小,通过这些解决方案在帧之间失去特定的延迟,等等)。此外,由于位置应该像素完美,因此即使可能调整大小也可能由于舍入误差而产生问题。
现在,有没有更好的方法来做到这一点? 我可以以某种方式加载GIF动画并手动合并它们(即使它们可能有不同数量的图层),所以我只能绘制一个图像?有没有可以手动设置组件位置的布局管理器,但如果调整窗口/面板的大小,它会自动缩放它?有没有第三方图形项目可以做我想要的东西?
理想情况下,我会做的事情,如果他们不是动画,如建立一个合并的图像,然后调整和显示那个。
全码:
import java.awt.Dimension;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public final class Tester extends JFrame {
public static void main(String[] args) throws MalformedURLException {
new Tester();
}
private Tester() throws MalformedURLException {
setTitle("Tester");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Icon backgroundIcon = new ImageIcon(new URL("http://s5.favim.com/orig/51/animated-gif-gif-hands-sign-language-Favim.com-542945.gif"));
Icon foregroundIcon = new ImageIcon(new URL("http://i.imgur.com/89HANHg.gif"));
JLabel background = new JLabel(backgroundIcon);
JLabel foreground = new JLabel(foregroundIcon);
// ugly
background.setSize(backgroundIcon.getIconWidth(), backgroundIcon.getIconHeight());
foreground.setSize(foregroundIcon.getIconWidth(), foregroundIcon.getIconHeight());
background.setLocation(0, 0);
foreground.setLocation(30, 30);
background.setLayout(null);
background.add(foreground);
setLayout(null);
add(background);
// set size of frame to size of content
setResizable(false);
getContentPane().setPreferredSize(new Dimension(backgroundIcon.getIconWidth(), backgroundIcon.getIconHeight()));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
在你的[sscce](http://sscce.org/)中,通过'URL'访问发布的图片,如[这里](http://stackoverflow.com/a/10862262/230513)或[below](http://stackoverflow.com/a/18434145/230513);如图所示使用合成图像(http://stackoverflow.com/a/15982915/230513);或使用'UIManager'图标,如[此处]所示(http://stackoverflow.com/a/12228640/230513)。 – trashgod
进行了相应编辑 – Klaue