我正在使用FontMetrics.getHeight()获取字符串的高度,但它给了我一个错误的值,切断了字符串字符的下降.我可以使用更好的功能吗?
ran*_*ibt 20
getStringBounds()下面的方法基于GlyphVector当前Graphics2D字体,它适用于一行文本字符串:
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();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,为了清楚起见,我省略了导入.
结果:

Joa*_*uer 12
是什么让你认为它返回错误的价值?你对它返回的预期与规范不符的可能性要大得多.请注意,如果Font中的某些字形超过或低于这些值,则完全正常.
getMaxDescent()并且getMaxAscent()应该告诉您Font中任何字形的那些字段的绝对最大值.
如果您想知道特定String的指标,那么您肯定想要调用getLineMetrics().