gpt4 book ai didi

java - 字体渲染中的换行

转载 作者:太空宇宙 更新时间:2023-11-04 07:12:29 24 4
gpt4 key购买 nike

所以我刚刚为我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com