sparklyllama
sparklyllama

Reputation: 1326

Line Break in Font Rendering

So I just created a Font sprite sheet for my Java Game, and have implemented this method into a class to draw text using that sprite sheet.

public static void renderText(Graphics2D g, String message, int x, int y, int size) {

    message = message.toUpperCase();
    for(int i = 0; i < message.length(); i++) {
        char c = message.charAt(i);
        if(c == 47) c = 36; // slash
        if(c == 58) c = 37; // colon
        if(c == 32) c = 38; // space
        if(c == 46) c = 40; // period
        if(c == 95) c = 39; // underscore
        if(c == 33) c = 41; // exclamation point
        if(c == 63) c = 42; // question mark
        if(c == 39) c = 43; // apostrophe
        if(c >= 65 && c <= 90) c -= 65; // letters
        if(c >= 48 && c <= 57) c -= 22; // numbers
        int row = c / font[0].length; // font is a 2D Array of BufferedImages from the sprite sheet 
        int col = c % font[0].length;
        g.drawImage(font[row][col], x + size * i, y, size, size, null);
    }

}

This all works fine, but the strings it renders are usually longer than the window. I tried using String newline = System.getProperty("line.separator"), but that gives me an error because when it tries to render that newline string, it doesn't know what character to use.

How could I test if the string is longer than the window and then implement some sort of line break?

Upvotes: 1

Views: 263

Answers (2)

AJMansfield
AJMansfield

Reputation: 4129

There is no reason you need to be rolling your own renderer. Using the system font renderer has a number of advantages, including the fact that it is able to take advantage of advanced caching and all sorts of other things that your graphics system is just begging to do if you will just let it. (Not to mention that it also actually works.)

If you want to display the text in a custom font face, then use a custom font face. A quick google turns up all sorts of results for how to create a font from images, create a custom font, or use an icon font generator. Once you have the font, add it as a resource to your project, similar to how you would add images, and use that.

Another related option is to define it as a new subclass of java.awt.Font.

Upvotes: 0

Mathias
Mathias

Reputation: 51

You could simply call font[row][col].getTileWidth() to get the pixel width of each sprite and ensure that the sum <= width of the panel.

Also, what's happening here?

if(c == 95) c = 39; // underscore
...
if(c == 39) c = 43; // apostrophe

Is that really the intent?

Upvotes: 1

Related Questions