我正在尝试将此 spritesheet 加载到缓冲图像数组中(每个 sprite 加载到一个 BufferedImage 中):
我在 Photoshop 上打开了这个文件。宽度是500,高度是666。所以根据我的计算,我需要循环64次(8行8列),对于每个 Sprite ,它的宽度是500/8(62.5),高度是666/8 (83.25)。由于 getSubImage 仅接受 int 参数,因此我被迫将宽度设置为 62,将高度设置为 83(我认为这就是它截断我的图像的原因)。
这是加载 Sprite 的代码(我将它们放入 JFrame 中以向您展示结果)。
public class Test{
public static void main(String [] args){
BufferedImage[] sprites = null;
int width = 62;
int height = 83;
try {
BufferedImage buff = ImageIO.read(Test.class.getResourceAsStream("cyclop.gif"));
sprites = new BufferedImage[64];
int rows = 8;
int cols = 8;
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
sprites[(i * cols) + j] = buff.getSubimage(i * width, j * height, width, height);
}
}
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
for(BufferedImage bf : sprites)
frame.getContentPane().add(new JLabel(new ImageIcon(bf)));
frame.pack();
frame.setVisible(true);
}
}
哪个输出:
我对如何加载 BufferedImage 中的每个 Sprite 有点迷失(第一次这样做)。有什么想法吗?
最佳答案
基本上就是你的逻辑for-loop
错了...
您正在乘以 width
按当前行 ( i
) 和 height
按当前列 ( j
)
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sprites[(i * cols) + j] = buff.getSubimage(i * width, j * height, width, height);
}
}
它应该更像......
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sprites[(i * cols) + j] = buff.getSubimage(j * width, i * height, width, height);
}
}
(例如,我将高度增加到第 95 行)
现在,显然,你有一个问题,因为 Sprite 的大小不同,对你来说是的。我建议创建一个简单的查找文件,其中包含行/列作为键以及单元格的宽度/高度,甚至可能是 x/y,因此您可以直接直接选择 Sprite ,但这取决于您。 ..
关于java - 加载 Sprite 表时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21370593/