import java.util.LinkedList;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.net.URL;
import java.awt.image.RasterFormatException;
public class SpriteSheet
{
// What we're going to store the images in
private BufferedImage[] images;
// Holds the location of our sprites
private URL loc;
// The image we'll grab our sprites from
private BufferedImage sprites;
// Tile size of each image
private int tileSizeX;
private int tileSizeY;
// Tiles in the image
private int xTiles;
private int yTiles;
SpriteSheet(String sourceLoc, int tX, int tY)
{
try
{
// Find where our resources are stored
loc = this.getClass().getResource(sourceLoc);
}catch(Exception e)
{
// Some error handling
System.out.println(sourceLoc + " is missing.");
e.printStackTrace();
}
try
{
// Get our resources from the URL
sprites = ImageIO.read(loc);
}catch(Exception e)
{
// Some error handling
System.out.println("Image missing or corrupted.");
e.printStackTrace();
}
// Amount of tiles in the x and y directions
xTiles = tX;
yTiles = tY;
// Array stores the images after they're split up
// The size is the amount of x tiles and y tiles (area)
images = new BufferedImage[xTiles * yTiles];
// Figure out the size of the tiles
tileSizeX = sprites.getWidth()/xTiles;
tileSizeY = sprites.getHeight()/yTiles;
// Do the actual splitting of the image into the array
loadSprites();
}
// Gets the instance of the spritesheet
public BufferedImage[] getSpritesheet() { return images;}
private void loadSprites()
{
BufferedImage temp;
for(int x = 0, y = 0, i = 0; ; x += tileSizeX)
{
temp = null;
System.out.println((sprites.getWidth() - x) + ", " + (sprites.getHeight() - y ));
try
{
temp = sprites.getSubimage(x, y, x + tileSizeX, y + tileSizeY);
}catch(RasterFormatException e)
{
System.out.println("Tile size is wrong, out of bounds.");
}
// Add the image to the array
images[i] = temp;
// Should stop the loop from getting outside the raster
if( i + 1 == images.length)
{
break;
}
// Makes the loop jump to the next row to load new images
if(i == xTiles)
{
y += tileSizeY;
x = 0;
}
i++;
}
}
}