以下是使用 Graphics2D 绘制图片的方法,在使用过程中,单笔调用都是居中。
但是如果换成批量调用,在生成部分图片中会出现部分行的文字不能正常居中的情况。
public static BufferedImage writeTextCenter(BufferedImage inputImage, int y, String text, Font font, Color color) throws IOException, FontFormatException {
Assert.notNull(inputImage, "input image is null");
Graphics2D graphics2d = inputImage.createGraphics();
graphics2d.setFont(font);
graphics2d.setColor(color);
graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
FontMetrics fontMetrics = graphics2d.getFontMetrics(font);
// 计算出中心点 x 位置
int centerX = inputImage.getWidth() / 2;
// 文字宽度
int textWidth = fontMetrics.stringWidth(text);
logger.info("centerX = [" + centerX + "], textWidth = [" + textWidth + "], text = [" + text + "]");
// 计算出中心点,并且绘制出文字
graphics2d.drawString(text, centerX - textWidth / 2, y);
graphics2d.dispose();
return inputImage;
}