首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FontMetrics返回错误的字符大小

FontMetrics返回错误的字符大小
EN

Stack Overflow用户
提问于 2018-02-11 00:21:24
回答 1查看 57关注 0票数 0

因为我在LWJGL项目中工作,所以它在显示文本时遇到了问题。理论上,我想遍历(扩展的) ascii表,并将所有字符的每个纹理保存到一个ArrayList中。

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

代码语言:javascript
复制
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;
}

有谁能帮帮我吗?或者,如果你有其他想法来解决这个问题,请让我知道

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-13 05:40:36

从字面上看,代码中的font.awtFont.deriveFont(100);行除了浪费时间之外什么也不做,它创建了一个新字体,然后立即丢弃它,并使用原来的字体。

Derive the new font,然后使用它:

代码语言:javascript
复制
....
Font bloodyHuge = font.awtFont.deriveFont(100);
graphics.setFont(bloodyHuge);
...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48722884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档