在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

以下是使用 Graphics2D 繪制圖片的方法,在使用過程中,單筆調(diào)用都是居中。
但是如果換成批量調(diào)用,在生成部分圖片中會出現(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);
        // 計算出中心點 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;
    }
回答
編輯回答
不將就

建議你 打印出字體,看看是不是字體導致的問題.

2017年8月16日 18:11