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

编程入门 行业动态 更新时间:2024-10-28 12:27:39
本文介绍了如何获得真正的字符串高度在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中?

本文发布于:2023-10-29 20:41:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1540696.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   如何获得   高度   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!