如何获得真正的字符串高度在Java中? [英] How to get real string height in Java?
本文介绍了如何获得真正的字符串高度在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用 FontMetrics.getHeight()
来获取字符串的高度,但它给了我一个错误的值,切断的字符串中的字符的下行。有没有更好的功能,我可以使用?
I'm using FontMetrics.getHeight()
to get the height of the string, but it gives me a wrong value, cutting off the descenders of string characters. Is there a better function I can use?
推荐答案
previous code:
Previous code:
protected float getLabelHeight(Graphics2D g2, String label)
{
FontRenderContext frc = g2.getFontRenderContext();
return LABEL_FONT.getLineMetrics(label, frc).getHeight();
}
目前的答案:
我所定义的 getStringBounds()
下面的方法,根据的GlyphVector
当前的Graphics2D
字体,这非常适用于文本的字符串:
I've defined the getStringBounds()
method below, based on the GlyphVector
for the current Graphics2D
font, which works very well for one string of text:
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 getTextBounds()
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();
}
});
}
}
请注意,我已经省略了进口清晰度。
Note that I've omitted the imports for clarity.
结果:
这篇关于如何获得真正的字符串高度在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文