Java 怎么绘制X居中的字符串

2019年8月20日22:29:10 评论 22

1.简介

Java 怎么绘制X居中的字符串?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import org.apache.log4j.Logger;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.util.*;
import java.util.regex.Pattern;

public class Main{
    public static final float drawXCenteredString(Graphics2D g,
            String string, Font font, float y, float centerX) {
        float textWidth = getTextWidth(g, string, font);
        float x = centerX - (textWidth / 2);
        return drawString(g, string, font, x, y);
    }
    public static final float getTextWidth(Graphics2D g, String string,
            Font font) {
        return g.getFontMetrics(font).stringWidth(string);
    }
    public static final float drawString(Graphics2D g, String string,
            Font font, float x, float y) {
        g.setFont(font);
        y += font.getLineMetrics(string, g.getFontRenderContext())
                .getAscent();
        g.drawString(string, x, y);
        return getTextHeight(g, string, font);
    }
    public static final float getTextHeight(Graphics2D g, String string,
            Font font) {
        LineMetrics lm = font.getLineMetrics(string,
                g.getFontRenderContext());
        return lm.getHeight();
    }
}

 

3.总结

示例代码演示了 Java 怎么绘制X居中的字符串,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: