Initially I was trying to access the BufferedImage graphics, and draw the string to the BufferedImage. I got the drawString method to work, but it wouldn’t change the font size when I set the font size. How can I draw a simple string to a 2D pixel array so that I don’t have to create a sprite sheet and handle fonts using the spirte sheet?
Please show us the relevant code you are using now, so that we can take a look and suggest improvements.
I do not get the 2d pixel array. But if you want to change a font size it can be managed with graphics2D setFont
private Font f = new Font("small pixel", Font.TRUETYPE_FONT, 20); // (font name, font type, font size)
public void render(Graphics2D g){ // rendering
g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello world in pixel font with color: red", 100,100);
}
or you can load a custom ttf font:
public void init(){
registerFont("font-name.ttf", 20);
}
private void registerFont(String fontName, int fontSize){
loadFont(Fonts.class, fontName, fontSize);
}
public Font loadFont(Class<?> classfile, String path, int size){
URL url = classfile.getResource(path); // get path to font
Font font = null;
try { // try and catch font
font = Font.createFont(Font.TRUETYPE_FONT, url.openStream());
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
font = font.deriveFont(Font.PLAIN, size);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font); // register font
return font; // returning font
}