如何在 Java 中将 Graphics.drawString() 居中?

新手上路,请多包涵

我目前正在为我的 Java 游戏开发菜单系统,我想知道如何将 Graphics.drawString() 中的文本居中,这样如果我想绘制一个中心点位于 X: 50 的文本 --- and Y: 50 , and the text is 30 pixels wide and 10 pixels tall, the text will start at X: 35 and Y: 45

我可以在绘制之前确定文本的宽度吗?

那么这将是简单的数学。

编辑: 我也想知道我是否可以获得文本的高度,以便我也可以将其垂直居中。

任何帮助表示赞赏!

原文由 Daniel Kvist 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

我用了 这个问题 的答案。

我使用的代码看起来像这样:

 /**
 * Draw a String centered in the middle of a Rectangle.
 *
 * @param g The Graphics instance.
 * @param text The String to draw.
 * @param rect The Rectangle to center the text in.
 */
public void drawCenteredString(Graphics g, String text, Rectangle rect, Font font) {
    // Get the FontMetrics
    FontMetrics metrics = g.getFontMetrics(font);
    // Determine the X coordinate for the text
    int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
    // Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
    int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
    // Set the font
    g.setFont(font);
    // Draw the String
    g.drawString(text, x, y);
}

原文由 Daniel Kvist 发布,翻译遵循 CC BY-SA 3.0 许可协议

当我必须绘制文本时,我通常需要将文本置于边界矩形的中心。

 /**
 * This method centers a <code>String</code> in
 * a bounding <code>Rectangle</code>.
 * @param g - The <code>Graphics</code> instance.
 * @param r - The bounding <code>Rectangle</code>.
 * @param s - The <code>String</code> to center in the
 * bounding rectangle.
 * @param font - The display font of the <code>String</code>
 *
 * @see java.awt.Graphics
 * @see java.awt.Rectangle
 * @see java.lang.String
 */
public void centerString(Graphics g, Rectangle r, String s,
        Font font) {
    FontRenderContext frc =
            new FontRenderContext(null, true, true);

    Rectangle2D r2D = font.getStringBounds(s, frc);
    int rWidth = (int) Math.round(r2D.getWidth());
    int rHeight = (int) Math.round(r2D.getHeight());
    int rX = (int) Math.round(r2D.getX());
    int rY = (int) Math.round(r2D.getY());

    int a = (r.width / 2) - (rWidth / 2) - rX;
    int b = (r.height / 2) - (rHeight / 2) - rY;

    g.setFont(font);
    g.drawString(s, r.x + a, r.y + b);
}

原文由 Gilbert Le Blanc 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题