BufferedImage 画文本实现按照格式自动换行换行

本文介绍了一种使用Java的Graphics2D在图片上写字并自动换行的方法。通过递归方式,根据设定的行宽和行高,计算字体位置,确保文字不会超出图片边界。适用于需要在图片上添加多行文字的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现方式

Java 使用Graphics2D图片上写字,计算宽和高 以及字体的位置。通过递归的方式画出的每一行。

代码实现

 	/**
     * 画换行文案
     *
     * @param base 图片
     * @param text 文案
     * @param x 横坐标
     * @param y 纵坐标
     * @param rowWidth 每行宽度
     * @param height 行高
     * @param widthRate 每个字符所占的长度
     * @param font 字体
     * @param color 颜色
     * @return
     */
    public static BufferedImage drawTextWithFontStyleLineFeed(BufferedImage base, String text, int x, int y,
                                                              int rowWidth, int height, Double widthRate, Font font, Color color) {
        Graphics2D g = (Graphics2D) base.getGraphics();
        g.setFont(font);
        g.setColor(color);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        drawTextLineFeed(g, base, text, rowWidth, height, x, y, widthRate);
        return base;
    }

   /**
	*  通过递归的方式由上到下画文案
	*/
    private static void drawTextLineFeed(Graphics2D g, BufferedImage base, String text, int rowWidth, int height, int loc_X, int loc_Y, Double widthRate) {
        int width = getStrWidth(base, text, widthRate);
        if (width <= rowWidth) {
            g.drawString(text, loc_X, loc_Y);
            return;
        }
        for (int i = 1; ; i++) {
            String str = text.substring(0, i);
            int localWidth = getStrWidth(base, str, widthRate);
            // 当字体宽度超过目标行宽,则输出当前文本
            if (localWidth >= rowWidth) {
                g.drawString(str, loc_X, loc_Y);
                int length = text.length();
                // 保存剩余的文本
                text = text.substring(i, length);
                break;
            }
        }
        // 画下一行
        drawTextLineFeed(g, base, text, rowWidth, height, loc_X,loc_Y + height, widthRate);
    }
	
   /**
	* 计算当前文案所占宽度
	*/
    private static int getStrWidth(BufferedImage base, String str, Double widthRate) {
        char[] c = str.toCharArray();
        Double width = base.getGraphics().getFontMetrics().charsWidth(c, 0, str.length()) * widthRate;
        return width.intValue();
    }

参考链接: https://blog.youkuaiyun.com/weixin_34221112/article/details/91636884

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值