java 画图 如何把文字居中

  Java 的BufferImage做图的时候 

  有的时候需要些文字并且将文字居中


方法1:

/**
 * 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);
}

  方法2:

/**
 * 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);
}


参考链接:https://stackoverflow.com/questions/27706197/how-can-i-center-graphics-drawstring-in-java


  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值