有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法获得正确的字体宽度

这是一种将awt字体字符作为缓冲区图像返回的方法:

private BufferedImage getCharImage(char ch) {
    BufferedImage sizeImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    Graphics2D sizeGraphics = (Graphics2D) sizeImage.getGraphics();
    if (antiAlias) {
        sizeGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    FontMetrics fontMetrics = sizeGraphics.getFontMetrics(font);
    int charwidth = fontMetrics.charWidth(ch);
    if (charwidth <= 0) {
        charwidth = 1;
    }

    int charheight = fontMetrics.getHeight();
    if (charheight <= 0) {
        charheight = fontSize;
    }

    BufferedImage charImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D charGraphics = (Graphics2D) charImage.getGraphics();

    if (antiAlias) {
        charGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    charGraphics.setFont(font);
    charGraphics.setColor(Color.WHITE);
    charGraphics.drawString(String.valueOf(ch), 0, fontMetrics.getAscent());

    return charImage;
}

问题是,我得到了不正确的宽度,字符不适合板条箱缓冲图像。如果我像这样创建缓冲图像new BufferedImage(charwidth + 10, charheight, BufferedImage.TYPE_INT_ARGB);,字符将适合图像(这意味着我得到了错误的字体宽度)我为什么要面对这个问题?我该如何解决它我正在使用arialbi。ttf(粗体、斜体)

这就是字体的呈现方式 enter image description here

编辑:

这是我如何定义字体变量的:

    font = Font.createFont(Font.TRUETYPE_FONT, inputStream);
    font = font.deriveFont(fontSize);

共 (2) 个答案

  1. # 1 楼答案

    我认为这是因为高级,或者charWidth()与字体定义的字符的实际宽度没有太大关系

    Javadoc对于FontMetrics.charWidth(char ch)

    The advance is the distance from the leftmost point to the rightmost point on the character's baseline

    大法官斜体字中的“g”等字符位于基线下方,延伸至最小x的左侧。相同字体中的“s”延伸至最大x的右侧,位于基线上方。在更直的字体中,如Arial Regular,前进(基线宽度)恰好非常接近字符的实际宽度

    除了添加任意填充之外,我不确定是否还有好的解决方案

    另见:http://docs.oracle.com/javase/tutorial/2d/text/measuringtext.html

  2. # 2 楼答案

    我相信这就是获得字符串确切宽度所需的:

    FontMetrics fontMetricesForLabel = graphics.getFontMetrics();
    double width = fontMetricesForLabel.getStringBounds(label, graphics).getWidth();