我想得到我的字符串的精确高度(以像素为单位)。所以我写了一个程序来画字符串,然后画一个矩形。
使用FontMetrics,我使用了方法来获得包围矩形。
然而,这看起来是错误的:

我原以为长方形能完美地包围我的文本,但是顶部有空间(左边和右边有一点空间)。为什么要给我这样的结果?
这是我的代码:
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);
}
}发布于 2016-04-07 13:27:14
对于您的矩形,您必须考虑字体的下降(它在线下有多远)
g.drawString(str, x, y - fm.getDescent());还请注意,字体高度通常考虑某种类型的行距。在本例中,fm.getDescent() + fm.getAscent() = 68,而fm.getHeight() = 70
发布于 2016-04-07 13:26:30
顶部的空间可以解释为您没有考虑到下降(这让我回到了Java1.0中我最喜欢的方法之一: getMaxDecent)。
否则,盒子看上去很不错。我唯一能提供的其他建议是,fm.getStringBounds在某些字体上比对其他字体工作得更好。
https://stackoverflow.com/questions/36477433
复制相似问题