FontMetrics returns 高度错误

FontMetrics returns wrong height

我想获得面板上字符串的准确高度(以像素为单位)。所以我写了一个程序来绘制字符串,然后在它周围绘制一个矩形。

使用 FontMetrics 我使用 getStringBounds 方法获取封闭矩形。

不过看起来不对:

我原以为矩形可以完美地包围我的文本,但顶部有 space(左右两边还有一点点 space)。为什么给我这个结果?

这是我的代码:

public class Test extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {

        Font font = new Font("Arial", Font.PLAIN, 60);
        g.setFont(font);

        FontMetrics fm = this.getFontMetrics(font);

        String str = "100dhgt";
        Rectangle2D rect = fm.getStringBounds(str, g);

        int x = 5;
        int y = 100; 

        g.drawRect(x, y - (int)rect.getHeight(), (int)rect.getWidth(), (int)rect.getHeight());
        g.drawString(str, x, y);
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();

        Test test = new Test();
        f.add(test);
        f.setVisible(true);
        f.setSize(400, 400);
    }

}

顶部的 space 可以解释为您没有考虑下降(这让我回到 java 1.0 中我最喜欢的方法之一:getMaxDecent)

否则,盒子看起来还不错。我能提供的唯一其他建议是 fm.getStringBounds 在某些字体上比在其他字体上效果更好

关于你的矩形,你必须考虑字体的下降(线下多远)

g.drawString(str, x, y - fm.getDescent());

另请注意,字体高度通常会考虑某种行间距。在这种情况下 fm.getDescent() + fm.getAscent() = 68 而 fm.getHeight() = 70