Java:我不明白这个 Sprite 表读取代码的部分意义是什么?

标签 java bufferedimage sprite-sheet

抱歉,这是一些代码,但这里没有太多需要删除的内容。这应该读取一个图像(字母表的 Sprite 表)并将其切成更小的子图像,每个子图像都是单独的字母。当按下某个键时,相应的字母会出现在屏幕上,但这部分仅用于创建实际的子图像。

/image/O7vv8.png (上图)

package typeandscreen;
(where the imports should be, i just cut them out to save space)
public class Font{

    final int width = 78; //gives the dimensions of the image
    final int height = 32;
    final int rows = 4;
    final int cols = 13;

BufferedImage letters[] = new BufferedImage[rows*cols]; //makes the array of
                                                        //subimages. rows*cols is
                                                        //the number of subimages
void test(){
    try{
        final BufferedImage totalImage = ImageIO.read(new File("ABCabcs.png"));
                //loads the big image itself

以下部分让我感到困惑。 i 和 j 的作用是什么?为什么要对它们进行加法和乘法?这部分是为了找出子图像必须有多大,对吗?难道不应该是 4 x 13,即 rows*cols 吗?

    for(int i = 0; i < rows; i++){

        for(int j = 0; j < cols; j++){
            letters[(i * cols) + j] = totalImage.getSubimage(
                j * width,
                j * height,
                width,
                height
            );
        }
    }
    } catch(IOException e){
        e.printStackTrace();
    }
  }
}

我不明白 i 和 j 在做什么。我在这里缺少什么?

最佳答案

应该是

 j * width,
 i * height,

而且宽度和高度对于单个字母的大小来说似乎太大了,但它们就是这样使用的。

i 遍历字母的行,j 遍历字母的列。要获取位置 (j,i) 处字母的坐标,您需要将 j(列索引)乘以宽度(即每个字母的宽度),将 i(行索引)乘以(字母的高度)。

letters 是与字母对应的图像数组。

 letters[(i * cols) + j]

是将矩形矩阵放入一维数组的标准习惯用法。看图:

  0 1 2
0 A B C
1 D E F

存储在数组中

0 1 2 3 4 5
A B C D E F

因此该数组中 F 的索引将为 1 * 3 + 2 = 5,其中 i = 1、j = 2 且 cols = 3(因为有 3 列)

关于Java:我不明白这个 Sprite 表读取代码的部分意义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9074105/

相关文章:

java - 在 Java 中检查对象是否是类的实例的更好方法

javascript - Fabric.js - 如何从 Sprite 表制作动画

ios - 什么样的图像应该进入 cocos2d ios 应用程序的 spritesheet 中?

iphone - 带有图层和子项的 Cocos2d CCSpriteBatchNode

java - Kotlin中如何避免重载冲突?

java - 使用JDK 7编译Java 6源文件 : pros and cons

尝试从图像字节数组生成缩略图时启动 Java 应用程序

java - 检查 java 中的 bufferedImage 使用了多少内存?

java - 在 MANIFEST.MF 文件中找不到属性 'JCabi-Version'

java - 我无法在 JPanel 上查看 BufferedImage 图像