0

抱歉,这是一些代码,但这里没有太多要删减的内容。这应该读取图像(字母表的精灵表)并将其切割成较小的子图像,这些子图像是每个单独的字母。当一个键被按下时,相应的字母会出现在屏幕上,但这部分只是为了创建实际的子图像。

http://i.imgur.com/4I4uX.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,即行*列吗?

    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 在做什么。我在这里想念什么?

4

1 回答 1

3

它应该是

 j * width,
 i * height,

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

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

字母是对应于字母的图像数组。

 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 列)

于 2012-01-31T03:59:15.253 回答