Skip to content

Instantly share code, notes, and snippets.

@stevensona
Created February 7, 2016 20:49
Show Gist options
  • Save stevensona/ac1b6a14fd8670f730a2 to your computer and use it in GitHub Desktop.
Save stevensona/ac1b6a14fd8670f730a2 to your computer and use it in GitHub Desktop.
Load and access sprites from Kenney.nl spritesheets with libgdx
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.XmlReader;
import com.badlogic.gdx.utils.XmlReader.Element;
import java.util.HashMap;
/**
* Created by adam on 2/7/2016.
*/
public class SpriteSheet {
HashMap<String, TextureRegion> sprites;
Texture texture;
public SpriteSheet(String filename) {
try {
XmlReader xmlReader = new XmlReader();
Element root = xmlReader.parse(Gdx.files.internal(filename));
sprites = new HashMap<String, TextureRegion>();
texture = new Texture(Gdx.files.internal(root.getAttribute("imagePath")));
for (Element subtexture : root.getChildrenByName("SubTexture")) {
sprites.put(subtexture.getAttribute("name"), new TextureRegion(
texture,
Integer.parseInt(subtexture.getAttribute("x")),
Integer.parseInt(subtexture.getAttribute("y")),
Integer.parseInt(subtexture.getAttribute("width")),
Integer.parseInt(subtexture.getAttribute("height"))
));
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
public TextureRegion getSpriteRegion(String name) {
return sprites.get(name);
}
}
@stevensona
Copy link
Author

Usage:

SpriteSheet sheet = new SpriteSheet("sprites.xml");
batch.draw(sheet.getSpriteRegion("sprite1.png", 0, 0); //draw sprite1.png at 0, 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment