Java:g.drawString()宽度和高度以像素为单位?
问题描述:
我用fontmetrics来确定绘制到jpanel的字符串的长度和高度,但它给了我不正确的测量。Java:g.drawString()宽度和高度以像素为单位?
我使用的字符串是:“你好世界,这是梦幻般的”
例如:一个画了默认字体的字符串;根据字体指标的尺寸是:身高:24;当我测量它时,它实际上是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一个公式或方法,其可以提供在像素中的字符串的实际高度和宽度。谢谢!
答
我也有这个问题。尝试使用FontMetrics
对象的方法getStringBounds(String,Graphics)
。
public Rectangle2D bounds = fm.getStringBounds("Hello World this is fantastic", g);
int Ilength = (int)bounds.getWidth();
int Iheight = (int)bounds.getHeight();
结帐这篇文章http://*.com/questions/23729944/java-how-to-visually-center-a-specific-string-not-just-a-font-in-a-rectangle/23730189#23730189 – 2014-10-11 06:34:02
您是否在绘制字符串之前设置了图形的字体? 'g.setFont(F)'。 – 2014-10-11 06:44:07
没有。现在我还没有设置字体。即时通讯只是使用默认。 – nathannn 2014-10-11 07:23:42