Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
epoxy
GitHub Repository: epoxy/proj11
Path: blob/master/SLICK_HOME/src/org/newdawn/slick/XMLPackedSheet.java
1456 views
1
package org.newdawn.slick;
2
3
import java.util.HashMap;
4
5
import javax.xml.parsers.DocumentBuilder;
6
import javax.xml.parsers.DocumentBuilderFactory;
7
8
import org.newdawn.slick.util.ResourceLoader;
9
import org.w3c.dom.Document;
10
import org.w3c.dom.Element;
11
import org.w3c.dom.NodeList;
12
13
/**
14
* A sprite sheet based on an XML descriptor generated from the simple slick tool
15
*
16
* @author kevin
17
*/
18
public class XMLPackedSheet {
19
/** The full sheet image */
20
private Image image;
21
/** The sprites stored on the image */
22
private HashMap sprites = new HashMap();
23
24
/**
25
* Create a new XML packed sheet from the XML output by the slick tool
26
*
27
* @param imageRef The reference to the image
28
* @param xmlRef The reference to the XML
29
* @throws SlickException Indicates a failure to parse the XML or read the image
30
*/
31
public XMLPackedSheet(String imageRef, String xmlRef) throws SlickException
32
{
33
image = new Image(imageRef, false, Image.FILTER_NEAREST);
34
35
try {
36
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
37
Document doc = builder.parse(ResourceLoader.getResourceAsStream(xmlRef));
38
39
NodeList list = doc.getElementsByTagName("sprite");
40
for (int i=0;i<list.getLength();i++) {
41
Element element = (Element) list.item(i);
42
43
String name = element.getAttribute("name");
44
int x = Integer.parseInt(element.getAttribute("x"));
45
int y = Integer.parseInt(element.getAttribute("y"));
46
int width = Integer.parseInt(element.getAttribute("width"));
47
int height = Integer.parseInt(element.getAttribute("height"));
48
49
sprites.put(name, image.getSubImage(x,y,width,height));
50
}
51
} catch (Exception e) {
52
throw new SlickException("Failed to parse sprite sheet XML", e);
53
}
54
}
55
56
/**
57
* Get a sprite by it's given name
58
*
59
* @param name The name of the sprite to retrieve
60
* @return The sprite from the sheet or null if the name isn't used in this sheet
61
*/
62
public Image getSprite(String name) {
63
return (Image) sprites.get(name);
64
}
65
}
66
67