Graphics2D 绘制文字,不能稳定居中

新手上路,请多包涵

以下是使用 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;
    }
阅读 7.9k
1 个回答

建议你 打印出字体,看看是不是字体导致的问题.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题