java - 加载 Sprite 表时出现问题

标签 java bufferedimage sprite-sheet

我正在尝试将此 spritesheet 加载到缓冲图像数组中(每个 sprite 加载到一个 BufferedImage 中):

enter image description here

我在 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);
    }
}

哪个输出:

enter image description here

我对如何加载 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);
    }
}

Sprites

(例如,我将高度增加到第 95 行)

现在,显然,你有一个问题,因为 Sprite 的大小不同,对你来说是的。我建议创建一个简单的查找文件,其中包含行/列作为键以及单元格的宽度/高度,甚至可能是 x/y,因此您可以直接直接选择 Sprite ,但这取决于您。 ..

关于java - 加载 Sprite 表时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21370593/

相关文章:

java - Spring MVC 既不是 BindingResult 也不是 bean 名称的普通目标对象

java - 创建具有长 :Java 的日期对象时未解决编译问题

java - 如何找到 Play Framework 应用程序的绝对路径?

javafx - 从带有背景和自动换行的文本创建图像

java - 与原始图像文件相比,ImageIO 写入产生不同的文件大小

java - 显示 BufferedImage 后如何对其进行编辑?

python - 改变 Sprite 动画速度(pygame)

java - 根据 ID 在 spritesheet 中显示纹理

ios - 当您在 Cocos2d 中加载纹理(使用 Sprite 表)时,内存使用量如何增加?

java - 当我尝试通过我的应用程序注册时,我没有收到任何回复