【问题标题】:FontMetrics returns wrong heightFontMetrics 返回错误的高度
【发布时间】:2016-04-07 13:18:10
【问题描述】:

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

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

}

【问题讨论】:

    标签: java swing java-2d


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 也考虑TextLayout,检查here
      • 所以边界有点像在横格纸上写文字? IE。就像在学校里,你必须在横线上写下 g 和 y。
      猜你喜欢
      • 1970-01-01
      • 2021-01-26
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      相关资源
      最近更新 更多