Average Density: 0.20
 1 package nl.tudelft.jpacman.sprite;
 2 
 3 import java.awt.Graphics;
 4 import java.awt.GraphicsConfiguration;
 5 import java.awt.GraphicsEnvironment;
 6 import java.awt.Image;
 7 import java.awt.Transparency;
 8 import java.awt.image.BufferedImage;
 9 
10 /**
11  * Basic implementation of a Sprite, it merely consists of a static image.
12  *
13  * @author Jeroen Roosen 
14  */
15 public class ImageSprite implements Sprite {
16 
17     /**
18      * Internal image.
19      */
20     private final Image image;
21 
22     /**
23      * Creates a new sprite from an image.
24      *
25      * @param img
26      *            The image to create a sprite from.
27      */
28     public ImageSprite(Image img) {
29         this.image = img;
30     }
31 
32     @Override
33     public void draw(Graphics graphics, int x, int y, int width, int height) {
34         graphics.drawImage(image, x, y, x + width, y + height, 0, 0,
35             image.getWidth(null), image.getHeight(null), null);
36     }
37 
38     @Override
39     public Sprite split(int x, int y, int width, int height) {
40         if (withinImage(x, y) && withinImage(x + width - 1, y + height - 1)) {
41             BufferedImage newImage = newImage(width, height);
42             newImage.createGraphics().drawImage(image, 0, 0, width, height, x,
43                 y, x + width, y + height, null);
44             return new ImageSprite(newImage);
45         }
46         return new EmptySprite();
47     }
48 
49     private boolean withinImage(int x, int y) {
50         return x < image.getWidth(null) && x >= 0 && y < image.getHeight(null)
51             && y >= 0;
52     }
53 
54     /**
55      * Creates a new, empty image of the given width and height. Its
56      * transparency will be a bitmask, so no try ARGB image.
57      *
58      * @param width
59      *            The width of the new image.
60      * @param height
61      *            The height of the new image.
62      * @return The new, empty image.
63      */
64     private BufferedImage newImage(int width, int height) {
65         GraphicsConfiguration gc = GraphicsEnvironment
66             .getLocalGraphicsEnvironment().getDefaultScreenDevice()
67             .getDefaultConfiguration();
68         return gc.createCompatibleImage(width, height, Transparency.BITMASK);
69     }
70 
71     @Override
72     public int getWidth() {
73         return image.getWidth(null);
74     }
75 
76     @Override
77     public int getHeight() {
78         return image.getHeight(null);
79     }
80 
81 }