Java 2D - 垂直居中的文本

问题描述 投票:0回答:2

我面临的问题是,我从字体度量对象中得到的下降值似乎不正确。只有在很大的字体上才会出现这种情况。我已经尝试过使用 FontMetrics#getDescent-办法,以及 FontMetrics#getStringBounds-方法,然后我使用 heighty 来手动计算出后裔。虽然两者给出的结果略有不同,但都不正确。对于一组预先定义的字符,最正确的方法是什么?在我的情况下,应该是字符 0-9. 这些都应该有相同的基线,因此容易居中。至少我的假设是这样的。

下面是一个展示问题的例子。

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.UIManager;


public class Draw
{
  public static void main( String[] args )
  {
    JFrame frame = new JFrame();
    frame.add( new X() );
    frame.pack();
    frame.setSize( 150, 300 );
    frame.setLocationRelativeTo( null );
    frame.setVisible( true );
  }

  private static class X extends JComponent
  {
    private final Font xFont;

    public X()
    {
      xFont = UIManager.getFont( "Label.font" ).deriveFont( 40.0f );
    }

    @Override
    public void paint( Graphics g )
    {
      g.setColor( Color.YELLOW );
      g.fillRect( 0, 0, getWidth(), getHeight() );

      g.setColor( Color.BLACK );
      g.drawLine( 0, getHeight() / 2, getWidth() - 1, getHeight() / 2 );

      g.setFont( xFont );
      g.drawString( "X", getWidth() / 2, getHeight() / 2 + g.getFontMetrics().getDescent() );
    }
  }
}

enter image description here

黑线代表组件的中间。的垂直中心。X 应该与该行对齐。

java swing graphics fonts java-2d
2个回答
3
投票

下面的方法似乎即使在大字体上也能用。 调整的方法是减去 leadingdescent 来自 ascent 并除以二。看来如果你不包括前导,大字体的文字就会出现漂移。在这个例子中,字体大小是 300. 对于较小的字体,这可能不是问题。

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawLine(0, getHeight() / 2, getWidth(),
            getHeight() / 2);
    g.setFont(xFont);
    String s = "X";
    FontMetrics fm = g.getFontMetrics();
    int swidth = fm.stringWidth(s);

    int ctrx = getWidth() / 2;
    int ctry = getHeight() / 2;

    int mheight = fm.getAscent() - fm.getDescent() - fm.getLeading();

    g.drawString(s, ctrx - swidth/2, ctry + mheight/2);
}

enter image description here


1
投票

我相信你想。

  FontMetrics fm =  g.getFontMetrics();
  g.drawString( "X", getWidth() / 2, (getHeight() + fm.getAscent() - fm.getDescent())/2 );

这给:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.