2016-04-07 40 views
1

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

使用的FontMetrics我用getStringBounds方法让我封闭的矩形。

但是它看起来错误:

enter image description here

我期待矩形完全包围我的文字,但在顶部(与空间上左边一点点,右),有空间。为什么它给了我这个结果?

这里是我的代码:

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

} 

回答

2

关于您的矩形做一些字体,你必须要考虑字体的降序(多远线以下)

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

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

2

上方的空间可以由您不考虑下降(这让我回想起我最喜欢的方法之一,从Java 1.0:getMaxDecent)来解释

否则,箱子看起来不错。我能提供的唯一的建议就是fm.getStringBounds工作更好地与比它与其他

+0

也考虑'TextLayout',审查[这里](http://stackoverflow.com/a/16014525/ 230513)。 – trashgod

+0

这样的界限有点​​像写在横格纸上的文字? IE浏览器。就像在学校里你必须写下g和y一样。 –

相关问题