鍍金池/ 問(wèn)答/Java/ Graphics2D 繪制文字,不能穩(wěn)定居中

Graphics2D 繪制文字,不能穩(wěn)定居中

以下是使用 Graphics2D 繪制圖片的方法,在使用過(guò)程中,單筆調(diào)用都是居中。
但是如果換成批量調(diào)用,在生成部分圖片中會(huì)出現(xiàn)部分行的文字不能正常居中的情況。

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);
        // 計(jì)算出中心點(diǎn) x 位置
        int centerX = inputImage.getWidth() / 2;
        // 文字寬度
        int textWidth = fontMetrics.stringWidth(text);
        logger.info("centerX = [" + centerX + "], textWidth = [" + textWidth + "], text = [" + text + "]");
        // 計(jì)算出中心點(diǎn),并且繪制出文字
        graphics2d.drawString(text, centerX - textWidth / 2, y);
        graphics2d.dispose();
        
        return inputImage;
    }
回答
編輯回答
不將就

建議你 打印出字體,看看是不是字體導(dǎo)致的問(wèn)題.

2017年8月16日 18:11