我正在尝试在 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);
使用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);