gpt4 book ai didi

java - FontMetrics 返回错误的字符大小

转载 作者:行者123 更新时间:2023-12-02 11:38:53 24 4
gpt4 key购买 nike

由于我从事 LWJGL 项目,因此遇到了显示文本的问题。理论上,我想迭代(扩展)ascii 表并将所有字符的每个纹理保存在 ArrayList 中。

但我的问题是,在创建字符图像时它不会获得正确的尺寸。尺寸似乎是 1(宽)x 3(高)代码:

private static BufferedImage createCharImage(Font font, char c) {
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = image.createGraphics();
// As you see, I set the font size to 100 for testing
font.awtFont.deriveFont(100);
graphics.setFont(font.awtFont);
FontMetrics fontMetrics = graphics.getFontMetrics();
graphics.dispose();
// Here the problem appears that the dimensions seem to be w: 1 and h: 3
Vector2i charDimensions = new Vector2i(fontMetrics.charWidth(c), fontMetrics.getHeight());

if (charDimensions.x == 0) {
return null;
}

image = new BufferedImage(charDimensions.x, charDimensions.y, BufferedImage.TYPE_INT_ARGB);
graphics = image.createGraphics();
graphics.setFont(font.awtFont);
graphics.setPaint(java.awt.Color.WHITE);
graphics.drawString(String.valueOf(c), 0, fontMetrics.getAscent());
graphics.dispose();

return image;
}

有人可以帮我吗?或者,如果您有其他想法来解决此问题,请告诉我

最佳答案

线路font.awtFont.deriveFont(100);目前,您的代码中除了通过创建新字体然后立即丢弃它并使用原始字体来浪费时间之外,实际上什么也没做。

Derive the new font然后使用它:

....
Font bloodyHuge = font.awtFont.deriveFont(100);
graphics.setFont(bloodyHuge);
...

关于java - FontMetrics 返回错误的字符大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48722884/

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