【问题标题】:Java: g.drawString() width and height in pixels?Java:g.drawString() 宽度和高度(以像素为单位)?
【发布时间】:2014-12-06 08:27:20
【问题描述】:

我使用 fontmetrics 来确定绘制到 jpanel 的字符串的长度和高度,但它给了我不正确的测量值。

我使用的字符串是:“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中是否有公式或方法可以提供以像素为单位的字符串的实际高度和宽度。谢谢!

【问题讨论】:

  • 在绘制字符串之前是否设置了图形的字体? g.setFont(f).
  • 没有。现在我还没有设置字体。我只是使用默认值。
  • 啊,我把它改成了 Times New Roman,它现在似乎可以工作了。
  • 改为获取GlyphVector的边界,如this answer所示..

标签: java string swing graphics fontmetrics


【解决方案1】:

我也有这个问题。尝试使用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();

【讨论】:

    猜你喜欢
    • 2011-12-05
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    相关资源
    最近更新 更多