简体   繁体   English

Java:g.drawString()宽度和高度以像素为单位?

[英]Java: g.drawString() width and height in pixels?

I used fontmetrics to determine the length and height of the String drawn to a jpanel but it gave me incorrect measurements. 我使用字体度量来确定绘制到jpanel上的String的长度和高度,但这给了我错误的度量。

The String I used was: "Hello World this is fantastic" 我使用的字符串是:“ Hello World,这太棒了”

For example: a drew a string with the default font; 例如:a用默认字体绘制了一个字符串; according to the font metrics the dimensions were: height: 24; 根据字体规格,尺寸为:高度:24; width: 224. 宽度:224。

when I measured it, it was in fact 148 pixels long and 10 pixels in height. 当我进行测量时,实际上它的长度为148像素,高度为10像素。 (basically by trial and error) (基本上是反复试验)

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);

I am wondering if there is a formula or method in java that can provide the actual height and width of the string in pixels. 我想知道java中是否有公式或方法可以提供以像素为单位的字符串的实际高度和宽度。 Thanks! 谢谢!

I also had this problem. 我也有这个问题。 Try to use the method getStringBounds(String,Graphics) of your FontMetrics object. 尝试使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM