账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Graphics2D 绘制文字,不能稳定居中
    40
    0

    以下是使用 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;
        }
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部