Graphics对文字换行画图

本文介绍了一个使用Java绘制文字到图片的示例代码。通过创建一个200x200像素的BufferedImage,并利用Graphics对象在其上绘制指定的文字。代码支持将长字符串分批绘制,确保文字能完全展示在图片内。
    public static File drawImage(String name) {
        try {
            // 获取图片的缓冲区,也就是所谓的画布
            BufferedImage bufferedImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
            //获取画笔,画笔用于在画布上进行绘制
            Graphics paint = bufferedImage.getGraphics();
            paint.setColor(new Color(0xE5E3E3));
            //绘制画布的背景色
            paint.fillRect(0, 0, 200, 200);
            Font font = new Font("微软雅黑", Font.BOLD, 40);
            paint.setFont(font);
            //设置画笔的颜色
            paint.setColor(new Color(0x0F0F10));
            //绘制显示的具体内容
            drawString(paint, name, bufferedImage, font);
            //绘制完成保存文件
            ImageIO.write(bufferedImage, "jpg", new FileOutputStream(name + ".jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new File(name + ".jpg");
    }

    public static void drawString(Graphics paint, String name, BufferedImage bufferedImage, Font font) {
        int length = name.length();
        int batchSize = 4;
        int round = length / batchSize;
        for (int i = 0; i <= round; i++) {
            int fromIndex = i * batchSize;
            int toIndex = (i < round) ? ((i + 1) * batchSize) : length;
            String splitName = name.substring(fromIndex, toIndex);
            paint.drawString(splitName, (bufferedImage.getWidth() - font.getSize() * splitName.length()) / 2, bufferedImage.getHeight() / 2 + (i * font.getSize() ));
        }
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值