【问题标题】:Center a drawn string relative to the window size?相对于窗口大小将绘制的字符串居中?
【发布时间】:2010-10-14 14:29:17
【问题描述】:

我正在尝试将使用 Java 中的 ""system", Font.BOLD, 90" 字体绘制的字符串居中。我试过 (width/2 - (font.size/2 * num_of_chars)) 但没用。

g2d.setFont(new Font("system", Font.BOLD, 90));
g2d.drawString("Pause", (int) ((800/2) - ((Font.getSize()/2) * 5)),270);

【问题讨论】:

  • 请添加示例代码或澄清您的问题 - 例如,您是否在 AWT 对象上绘图?不行怎么办?

标签: java string center


【解决方案1】:

使用getFontMetrics().getStringBounds(String, Graphics) 获取字符串与当前字体的边界。

所以它看起来像这样:

g2d.setFont(new Font("system", Font.BOLD, 90));
String msg = "Pause";
Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(msg, g2d);
g2d.drawString(msg, (int) ((getWidth() + bounds.getWidth()) / 2), 270);

【讨论】:

  • 有没有办法让 getStringBounds() 返回一个 rect 而不是一个 rect2D?
  • 编辑:没关系。我看到 2D 也有一个 getWidth 方法。谢谢。
猜你喜欢
  • 2023-03-20
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
相关资源
最近更新 更多