我在 Slick 中遇到问题,我想加载一个自定义容器文件(其中包含例如几百个图像)。但是我到底该怎么做呢?我将 Slick 用于我的游戏,它会有动画。Slick 的动画需要一个图像数组。现在想象一下,如果你想显示一个由 300 个图像组成的更复杂的动画,手动加载和创建图像对象是一个非常痛苦的过程。为了解决这个问题,我想到了这样一个容器类,它打开容器并返回图像(或其他任何东西!)。将图像保存回容器也很酷:P
那么有什么想法吗?
感谢您提供如何提前解决该问题的任何提示。
问候
我在 Slick 中遇到问题,我想加载一个自定义容器文件(其中包含例如几百个图像)。但是我到底该怎么做呢?我将 Slick 用于我的游戏,它会有动画。Slick 的动画需要一个图像数组。现在想象一下,如果你想显示一个由 300 个图像组成的更复杂的动画,手动加载和创建图像对象是一个非常痛苦的过程。为了解决这个问题,我想到了这样一个容器类,它打开容器并返回图像(或其他任何东西!)。将图像保存回容器也很酷:P
那么有什么想法吗?
感谢您提供如何提前解决该问题的任何提示。
问候
If you have all your images in a directory or file directory, its pretty easy to traverse the directories and make a list or map of all the images via java's File class and some recursion. Something like...
Map <String, Image> nameToImage = new HashMap<>();
public void addDefaultImages(){
this.addAndRecurseDirectoryOfImages(DEFAULT_IMAGE_DIRECTORY);
}
public void addAndRecurseDirectoryOfImages(String directory) {
File folder = new File(directory);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
nameToImage.put(listOfFiles[i].getName(), new Image(directory + "/" + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
addAndRecurseDirectoryOfImages(directory + "/" + listOfFiles[i].getName());
}
}
}
Then you can get images via the image name:
nameToImage.get(filename);
You can also add some logic to strip off the file extension.
BUT! There is a catch! If you package your application up one day, say, in a .jar file, Jar files have no concept of a file system! Meaning this won't work! In that case you'll want to generate a file that has a list of all your image locations because you won't be able to traverse directories.