Java根据字符串生成图片居中

本文介绍了一段使用Java代码实现的简单程序,通过BufferedImage和Graphics2D绘制'感谢支持'的文字,同时探讨了字体选择、颜色设置和字符尺寸调整。展示了如何将文字转换为图像并保存为JPEG文件。
摘要由CSDN通过智能技术生成

1.代码

package main;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class DrawClass {

    public static void main(String[] args) {
        String value = "感谢支持";
        paint(400, 400, 80, value);
    }

    /**
     * @param width    宽
     * @param height   高
     * @param fontSize 1个字符    180
     *                 2个字符    140
     *                 3个字符    100
     *                 4个字符     80,大概
     * @param value    要转的内容
     */
    public static void paint(int width, int height, int fontSize, String value) {
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
        //黑底
        graphics2D.setColor(Color.BLACK);
        graphics2D.fillRect(0, 0, width, height);
        //橙字
        graphics2D.setColor(Color.ORANGE);

        Font font = new Font("黑体", Font.BOLD, fontSize);
        graphics2D.setFont(font);
        //居中
        FontMetrics fontMetrics = graphics2D.getFontMetrics(font);
        int x = (width - fontMetrics.stringWidth(value)) / 2;
        //这个是我瞎猜的
        int y = height / 2 - font.getSize() * 4 / 5 + fontMetrics.getHeight();
        graphics2D.drawString(value, x, y);
        graphics2D.dispose();
        write(bufferedImage, "jpg", new File(value + ".jpg"));
    }

    public static void write(BufferedImage bufferedImage, String formatName, File target) {
        try {
            ImageIO.write(bufferedImage, formatName, target);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


2.大概效果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值