FontMetrics 返回错误的高度

Oli*_*ins 2 java swing java-2d

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

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

然而它看起来是错误的:

在此输入图像描述

我期望矩形能够完美地包围我的文本,但顶部有空间(左侧和右侧有一点空间)。为什么它给我这个结果?

这是我的代码:

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

mtj*_*mtj 5

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

g.drawString(str, x, y - fm.getDescent());
Run Code Online (Sandbox Code Playgroud)

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