Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package game1;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
- import javax.imageio.ImageIO;
- public class SpriteArray
- {
- //sprite array
- private BufferedImage[][] sprites;
- private int spriteXCount;
- private int spriteYCount;
- //main constructor:
- public SpriteArray(String file, int spriteWidth, int spriteHeight)
- {
- //create File from filename sent in string
- File imageFile = new File(file);
- //create BufferedImage to hold image read from file
- BufferedImage image = null;
- //read image from file supplied, throw exception if it fails
- try
- {
- image = ImageIO.read(imageFile);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- //returns width and height of image, used to calculate number of sprites
- int cellWidth = image.getWidth();
- int cellHeight = image.getHeight();
- //calculate number of sprites in spritesheet
- spriteXCount = cellWidth / spriteWidth;
- spriteYCount = cellHeight / spriteHeight;
- //allocate memory for required number of images in 'sprites' array
- sprites = new BufferedImage[spriteXCount][spriteYCount];
- //apply each subimage (sprite from spritesheet) to each element in the array
- for (int i = 0; i < spriteXCount; i++)
- {
- for (int j = 0; j < spriteYCount; j++)
- {
- sprites[i][j] = image.getSubimage( (spriteWidth * i) , (spriteHeight * j), spriteWidth, spriteHeight);
- }
- }
- }
- public BufferedImage[][] getSprites()
- {
- return sprites;
- }
- public BufferedImage getSpriteElement(int i, int j)
- {
- return sprites[i][j];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement