【问题标题】:How to center a drawString in Java? [closed]如何在 Java 中使 drawString 居中? [关闭]
【发布时间】:2015-12-27 20:25:04
【问题描述】:

如何在 Java 中使 drawString 的文本居中?我希望它可以动态地沿屏幕居中,无论我是否更改框的高度和宽度。我找到了this code但我不知道如何使用它。谁能解释一下?

【问题讨论】:

  • 那篇文章中的答案有一些有据可查的方法。
  • “我不知道怎么用”的哪一部分你卡住了
  • but I don't know how to use it. can someone explain?。第一次复制代码,第二次粘贴代码,第三次查看编译时会发生什么,第四次分析它,如果你卡住并且有错误,然后发布 your MCVE跨度>

标签: java string graphics


【解决方案1】:

水平...

String text = "...";
Graphics2D g2d = (Graphics2D)g.create();
FontMetrics fm = g2d.getFontMetrics();
int x = (getWidth() - fm.stringWidth(text)) / 2;

垂直...

String text = "...";
Graphics2D g2d = (Graphics2D)g.create();
FontMetrics fm = g2d.getFontMetrics();
int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();

还演示了here

也可以看看2D GraphicsWorking with Text APIs

【讨论】:

    猜你喜欢
    • 2012-01-16
    • 2017-01-18
    • 2020-12-21
    • 2016-02-19
    • 2017-07-31
    • 2021-05-12
    • 2021-10-17
    • 2013-03-04
    • 2011-11-21
    相关资源
    最近更新 更多