我使用fontmetrics来确定绘制到jpanel的String的长度和高度,但它给了我不正确的测量值。
我使用的字符串是:" Hello World这太棒了"
例如:a绘制了一个默认字体的字符串;根据字体指标,尺寸为:高度:24;宽度:224。
当我测量它时,它实际上是148像素长,10像素高。 (基本上通过反复试验)
FontMetrics fm = g.getFontMetrics(this.f);
int Ilength = fm.stringWidth("Hello World this is fantastic");
int Iheight = fm.getHeight();
System.out.println("height: " + Iheight + "; width: " + Ilength);
我想知道java中是否有一个公式或方法可以提供字符串的实际高度和宽度(以像素为单位)。谢谢!
答案 0 :(得分:0)
我也有这个问题。尝试使用getStringBounds(String,Graphics)
对象的FontMetrics
方法。
public Rectangle2D bounds = fm.getStringBounds("Hello World this is fantastic", g);
int Ilength = (int)bounds.getWidth();
int Iheight = (int)bounds.getHeight();