java - 字体渲染中的换行

标签 java line break

所以我刚刚为我的 Java 游戏创建了一个 Font sprite 表,并将此方法实现到一个类中以使用该 sprite 表绘制文本。

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);
    }

}

这一切都工作正常,但它渲染的字符串通常比窗口长。我尝试使用 String newline = System.getProperty("line.separator") ,但这给了我一个错误,因为当它尝试渲染 newline 时字符串,它不知道要使用什么字符。

如何测试字符串是否比窗口长,然后实现某种换行符?

最佳答案

您可以简单地调用font[row][col].getTileWidth()来获取每个 Sprite 的像素宽度,并确保总和<=面板的宽度。

另外,这里发生了什么?

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

这真的是意图吗?

关于java - 字体渲染中的换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20448749/

相关文章:

python - 简单的 while 循环直到在 Python 中中断

Java GC日志分析

JavaMail 将附件作为 base64 添加到 Mime 正文

java - 默认按钮的方法

c# - 修改文本文件中特定行的内容

c++ - 在 C++ 中如何跳出嵌套循环?

java - 使用 java 处理 azure blob 的 StorageException

python - 如何在 pygame 中添加一条线作为 Sprite ?

ios - 使用 Sprite Kit 在 Swift 中绘制直线,创建多条线

powershell - 使用powershell在文本文件中找到特定行后如何停止Get-Content -wait?按需退出管道