【问题标题】:FontMetrics returning wrong character sizeFontMetrics 返回错误的字符大小
【发布时间】:2018-02-10 16:21:23
【问题描述】:

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

但我的问题是它在创建 char 图像时无法获得正确的尺寸。尺寸似乎是 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;
}

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

【问题讨论】:

  • 你能把这里看起来无关紧要的代码去掉,然后在graphics.dispose() 后面加上System.out.println(fontMetrics.charWidth(c), fontMetrics.getHeight()) 之类的吗?主要是为了获得更好的minimal reproducible example。关于这一点,你能稍微改写一下,让代码成为一个简单的独立演示器吗?通常在这样做时,您最终会发现问题,您甚至不需要发布到 SO,但如果您不这样做,结果是提出问题的完美代码,而不是无法自行运行的代码.
  • 使用标准 java 这会起作用 - 可能也不准确,因为字体很复杂,但至少它会给你一些数字 - 我不知道这个 font.awtFont. 显然来自 gWiggle 的来源

标签: java fonts lwjgl fontmetrics


【解决方案1】:

您代码中的font.awtFont.deriveFont(100); 行目前实际上并没有做任何事情,除了浪费时间创建一个新字体然后立即丢弃它并改用原始字体。

Derive the new font 然后使用它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多