在java中获取字符串大小(没有可用的Graphics对象)

Luk*_*pas 12 java string graphics2d bounds

我正在尝试编写需要使用Java中的Graphics2D类绘制许多字符串的应用程序.我需要获取每个String对象的大小(以计算每个字符串的确切位置).在调用paint()方法之前应该完成很多字符串,并且在程序开始时只执行一次(所以我还没有Graphics2D对象).我知道有一个方法Font.getStringBounds()但它需要一个FontRenderContext对象作为参数.

当我试图创建自己的对象时:

FontRenderContext frc = new FontRenderContext(MyFont.getTransform(), true, true)
Run Code Online (Sandbox Code Playgroud)

然后获取字符串边界我总是得到不同的大小,而不是我在paint()方法中使用Graphics2D.getFontRenderContext()方法获得FontRenderContext.差异不大(约1E-3),但我想知道为什么会有任何区别?

但是,有没有更好更安全的方法来获取字符串的大小?

Thnx提前提供任何帮助!

Alb*_*rto 6

尝试使用FontMetrics类; 该stringWidth方法返回一个字符串的大小.一个例子:

JComponent c = getSomeKindOfJComponent();
FontMetrics fm = c.getFontMetrics(c.getFont()); // or another font
int strw = fm.stringWidth("My text");
Run Code Online (Sandbox Code Playgroud)

  • stringWidth不返回字符串的有效大小,因为它不考虑抗锯齿和其他功能(如字符之间的间距). (3认同)