如何在Java中获得真正的字符串高度?

2022-09-02 05:26:38

我用来获取字符串的高度,但它给了我一个错误的值,切断了字符串字符的降序。有没有更好的功能可以使用?FontMetrics.getHeight()


答案 1

下面的方法基于 for 当前字体,它非常适合一行文本字符串:getStringBounds()GlyphVectorGraphics2D

public class StringBoundsPanel extends JPanel
{
    public StringBoundsPanel()
    {
        setBackground(Color.white);
        setPreferredSize(new Dimension(400, 247));
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);

        // must be called before getStringBounds()
        g2.setFont(getDesiredFont());

        String str = "My Text";
        float x = 140, y = 128;

        Rectangle bounds = getStringBounds(g2, str, x, y);

        g2.setColor(Color.red);
        g2.drawString(str, x, y);

        g2.setColor(Color.blue);
        g2.draw(bounds);

        g2.dispose();
    }

    private Rectangle getStringBounds(Graphics2D g2, String str,
                                      float x, float y)
    {
        FontRenderContext frc = g2.getFontRenderContext();
        GlyphVector gv = g2.getFont().createGlyphVector(frc, str);
        return gv.getPixelBounds(null, x, y);
    }

    private Font getDesiredFont()
    {
        return new Font(Font.SANS_SERIF, Font.BOLD, 28);
    }

    private void startUI()
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(this);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) throws Exception
    {
        final StringBoundsPanel tb = new StringBoundsPanel();

        SwingUtilities.invokeAndWait(new Runnable()
        {
            public void run()
            {
                tb.startUI();
            }
        });
    }
}

请注意,为了清楚起见,我省略了导入。

结果:

Result screenshot.


答案 2

是什么让你认为它返回了错误的值?更有可能的是,您对它返回的内容的期望与规范不匹配。请注意,如果字体中的某些字形超过或低于这些值,则完全没问题。

getMaxDescent()并应告诉您字体中任何字形的这些字段的绝对最大值。getMaxAscent()

如果您想知道特定字符串的指标,那么您肯定要调用 。getLineMetrics()


推荐