Yeah, I know it’s not really that much, but it makes things a whole heck of a lot easier when I’m dealing with pulling characters off of different sheets.
So, here it goes…
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
/**
Makes it easy to take individual sections of a picture for use elsewhere, as in a spritesheet.
*/
public class SpriteSheet{
String name;
BufferedImage pic;
SpriteSheet(String s){
name=s;
try{
pic=ImageIO.read(getClass().getResource(s));
}catch(Exception e){
System.out.println("Could not initialize spritesheet");
pic=null;
}
}
public BufferedImage getPic(int x, int y, int width, int height){
BufferedImage retval;
int trans=pic.getColorModel().getTransparency();
Graphics2D temp;
GraphicsConfiguration gc=GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
retval=gc.createCompatibleImage(width,height,trans);
temp=retval.createGraphics();
temp.drawImage(pic,0,0,width,height,x,y,x+width,y+height,null);
temp.dispose();
}
public BufferedImage getPic(int x, int y, int width, int height, boolean reversed){
BufferedImage retval;
int trans=pic.getColorModel().getTransparency();
Graphics2D temp;
GraphicsConfiguration gc=GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
retval=gc.createCompatibleImage(width,height,trans);
temp=retval.createGraphics();
if(reversed)
temp.drawImage(pic,width,0,0,height,x,y,x+width,y+height,null);
else
temp.drawImage(pic,0,0,width,height,x,y,x+width,y+height,null);
temp.dispose();
}
public BufferedImage[] getPicArray(int x, int y, int width, int height, int num){
BufferedImage[] retval=new BufferedImage[num];
for(int i=0;i<num;i++){
retval[i]=getPic(x,y,width,height);
x+=width;
}
return retval;
}
public BufferedImage[] getPicArray(int x, int y, int width, int height, int num, boolean reversed){
BufferedImage[] retval=new BufferedImage[num];
for(int i=0;i<num;i++){
retval[i]=getPic(x,y,width,height,reversed);
x+=width;
}
return retval;
}
public BufferedImage[][] getDoublePicArray(int x, int y, int width, int height, int num1, int num2){
BufferedImage[][] retval=new BufferedImage[num2][];
for(int i=0;i<num2;i++){
retval[i]=getPic(x,y,width,height,num1);
y+=height;
}
return retval;
}
public BufferedImage[][] getDoublePicArray(int x,int y,int width,int height,int num1,int num2,boolean reversed){
BufferedImage[][] retval=new BufferedImage[num2][];
for(int i=0;i<num2;i++){
retval[i]=getPicArray(x,y,width,height,num1,reversed);
y+=height;
}
return retval;
}
}
I’ve expanded it a bit but what I added was too application-specific.