在Java中获取字符串大小(没有可用的Graphics对象) [英] Getting string size in java (without having a Graphics object available)

查看:80
本文介绍了在Java中获取字符串大小(没有可用的Graphics对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write application which need to draw many strings using Graphics2D class in Java. I need to get sizes of each String object (to calculate exact position of each string). There are so many strings that it should be done before the paint() method is called and only once at the beginning of my program (so then I don't have Graphics2D object yet). I know that there is a method Font.getStringBounds() but it needs a FontRenderContext object as a parameter.

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

When i tried to create my own object:

FontRenderContext frc = new FontRenderContext(MyFont.getTransform(), true, true)

然后获得字符串边界,与使用paint()内的Graphics2D.getFontRenderContext()方法获得FontRenderContext时相比,我得到的大小总是不同的.差异不大(大约1E-3),但我想知道为什么根本没有差异?

and then obtain the strings bounds I've always get different sizes than when I obtain FontRenderContext using Graphics2D.getFontRenderContext() method inside paint(). The differences are not big (about 1E-3) but I wonder why there is any difference at all?

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

However, is there any better and secure way to obtain sizes of a string?

Thnx提前提供任何帮助!

Thnx for any help in advance!

推荐答案

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

Try with the FontMetrics class; the stringWidth method returns the size of a string. An example:

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

这篇关于在Java中获取字符串大小(没有可用的Graphics对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆