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

Dan*_*ist 30 java text draw graphics2d centering

我目前正在为我的菜单系统上的Java游戏,我不知道如何可以从中心的文本Graphics.drawString(),因此,如果我想画一个文本,其中心点是在X: 50Y: 50,和文字30像素宽,10像素高,文本将从X: 35和开始Y: 45.

在绘制文本之前,我可以确定文本的宽度吗?
然后这将很容易数学.

编辑:我也想知道我是否可以获得文本的高度,这样我也可以垂直居中.

任何帮助表示赞赏!

Dan*_*ist 60

我在这个问题上使用了答案.

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

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果Graphics g来自系统,则不应将其丢弃. (13认同)
  • 请注意,此方法不使用给定矩形的 x 和 y。相反,它应该是 int x = rect.x + (rect.width -metrics.stringWidth(text)) / 2; 和 int y = rect.y + ((rect.height -metrics.getHeight()) / 2) +metrics.getAscent(); (3认同)

Gil*_*anc 7

当我必须绘制文本时,我通常需要将文本居中放置在一个边界矩形中。

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)