简体   繁体   中英

Java: I don't understand the point of part of this sprite-sheet reading code?

Sorry, this is a bit of code, but there's not much to cut out here. This is supposed to read an image(a sprite-sheet of the alphabet) and cut it into smaller subImages that are each individual letter. When a key is pressed, the corresponding letter goes on the screen, but this part is just for creating the actual sub-image.

http://i.imgur.com/4I4uX.png (the image)

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

This following part is what confuses me. What is i and j for, and why is it adding and multiplying them? This part is for finding out how big the subimages have to be, right? Shouldn't it just be 4 by 13, which is 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 don't get what the i and j are doing. What am I missing here?

It should be

 j * width,
 i * height,

And also width and height seem to be too big for the size of a single letter but they are used as such.

i goes through the rows of letters, j goes through the columns. To get coordinates of letter at position (j,i) you need to multiple j (index of column) by width (which is width of each letter) and i (index of row) by height (of a letter).

letters is the array of images which correspond to letters.

 letters[(i * cols) + j]

is the standard idiom for putting a rectangular matrix into 1-D array. See the picture:

  0 1 2
0 A B C
1 D E F

get stored in an array as

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

so the index of F in this array will be 1 * 3 + 2 = 5 where i = 1, j = 2 and cols = 3 (because there are 3 columns)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM