Skip to content

Commit

Permalink
Allow ImageTile images to come from a file or a URL. This makes
Browse files Browse the repository at this point in the history
ImageTile play nicely with Class.getResource().
  • Loading branch information
zathras committed Aug 24, 2018
1 parent 448074c commit d9a64d2
Showing 1 changed file with 49 additions and 12 deletions.
61 changes: 49 additions & 12 deletions src/edu/calpoly/spritely/ImageTile.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;

/**
Expand Down Expand Up @@ -76,24 +77,60 @@ public ImageTile(File imageFile, Size size, char text)
System.err.println("*** Error reading " + imageFile);
throw ex;
}
if (im.getWidth() != size.width || im.getHeight() != size.height) {
double scaleX = ((double) size.width) / im.getWidth();
double scaleY = ((double) size.height) / im.getHeight();
BufferedImage after =
new BufferedImage(size.width, size.height,im.getType());
AffineTransform scale =
AffineTransform.getScaleInstance(scaleX, scaleY);
AffineTransformOp scaleOp =
new AffineTransformOp(scale,
AffineTransformOp.TYPE_BILINEAR);
scaleOp.filter(im, after);
im = after;
im = scaleImage(im, size);
}
this.image = im;
this.text = text;
}

/**
* Create a ImageTile with the given image, at the given size,
* and that is represented by the given character when in text
* mode. The image may contain transparent and semi-transparent pixels.
*
* @param imageURL A url referring to a valid image file
* @param size The size of a tile, in pixels
* @param text The character representation of this tile
* in text mode
* @throws IOException if there is an error reading the image
* @see ImageIO#read(File)
*/
public ImageTile(URL imageURL, Size size, char text)
throws IOException
{
BufferedImage im;
if (GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadless()) {
im = null;
} else {
try {
im = ImageIO.read(imageURL);
} catch (IOException ex) {
System.err.println("*** Error reading " + imageURL);
throw ex;
}
im = scaleImage(im, size);
}
this.image = im;
this.text = text;
}

private static BufferedImage scaleImage(BufferedImage im, Size size) {
if (im.getWidth() != size.width || im.getHeight() != size.height) {
double scaleX = ((double) size.width) / im.getWidth();
double scaleY = ((double) size.height) / im.getHeight();
BufferedImage after =
new BufferedImage(size.width, size.height,im.getType());
AffineTransform scale =
AffineTransform.getScaleInstance(scaleX, scaleY);
AffineTransformOp scaleOp =
new AffineTransformOp(scale,
AffineTransformOp.TYPE_BILINEAR);
scaleOp.filter(im, after);
im = after;
}
return im;
}

@Override
public void paint(Graphics2D g, Size size) {
g.drawImage(image, 0, 0, null);
Expand Down

0 comments on commit d9a64d2

Please sign in to comment.