89 lines
2.2 KiB
Java
89 lines
2.2 KiB
Java
package dev.kske.chess.ui;
|
|
|
|
import java.awt.Image;
|
|
import java.awt.image.BufferedImage;
|
|
import java.io.IOException;
|
|
import java.util.Arrays;
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
import javax.imageio.ImageIO;
|
|
|
|
import dev.kske.chess.board.Piece;
|
|
|
|
/**
|
|
* Project: <strong>Chess</strong><br>
|
|
* File: <strong>TextureUtil.java</strong><br>
|
|
* Created: <strong>01.07.2019</strong><br>
|
|
* Author: <strong>Kai S. K. Engelbart</strong>
|
|
*/
|
|
public class TextureUtil {
|
|
|
|
private static Map<String, Image> textures = new HashMap<>(), scaledTextures = new HashMap<>();
|
|
|
|
static {
|
|
loadPieceTextures();
|
|
scaledTextures.putAll(textures);
|
|
}
|
|
|
|
private TextureUtil() {}
|
|
|
|
/**
|
|
* Loads a piece texture fitting to a piece object
|
|
*
|
|
* @param piece The piece from which the texture properties are taken
|
|
* @return The fitting texture
|
|
*/
|
|
public static Image getPieceTexture(Piece piece) {
|
|
String key = piece.getType().toString().toLowerCase() + "_" + piece.getColor().toString().toLowerCase();
|
|
return scaledTextures.get(key);
|
|
}
|
|
|
|
/**
|
|
* Scales all piece textures to fit the current tile size
|
|
*/
|
|
public static void scalePieceTextures(int scale) {
|
|
scaledTextures.clear();
|
|
textures
|
|
.forEach((key, img) -> scaledTextures.put(key, img.getScaledInstance(scale, scale, Image.SCALE_SMOOTH)));
|
|
}
|
|
|
|
/**
|
|
* Loads an image from a file in the resource folder.
|
|
*
|
|
* @param fileName The name of the image resource
|
|
* @return The loaded image
|
|
*/
|
|
private static Image loadImage(String fileName) {
|
|
BufferedImage in = null;
|
|
try {
|
|
in = ImageIO.read(TextureUtil.class.getResourceAsStream(fileName));
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
return in;
|
|
}
|
|
|
|
/**
|
|
* Load every PNG file inside the res/pieces directory.
|
|
* The filenames without extensions are used as keys in the map textures.
|
|
*/
|
|
private static void loadPieceTextures() {
|
|
Arrays
|
|
.asList("king_white",
|
|
"king_black",
|
|
"queen_white",
|
|
"queen_black",
|
|
"rook_white",
|
|
"rook_black",
|
|
"knight_white",
|
|
"knight_black",
|
|
"bishop_white",
|
|
"bishop_black",
|
|
"pawn_white",
|
|
"pawn_black")
|
|
.forEach(name -> textures.put(name, loadImage("/pieces/" + name + ".png")));
|
|
}
|
|
|
|
}
|