Java画图drawString居中(字符串在图片居中)

Java在操作图片的时候,往图片写入文本,如何让文本在图片居中,最重要的一点是获取字符串的长度

//得到该字体字符串的长度  
public static int getWordWidth(Font font, String content) {
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        int width = 0;
        for (int i = 0; i < content.length(); i++) {
            width += metrics.charWidth(content.charAt(i));
        }
        return width;
    }


    @Test
    public void Test2() throws IOException {
        int width=200;
        int height=300;
        //创建图片
        BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = bufferedImage.createGraphics();
        graphics.setColor(Color.CYAN);
        //设置背景
        graphics.fillRect(0,0,width,height);
        //定义文本
        String text="看我居中";
        //定义字体
        Font font = new Font("微软雅黑", Font.PLAIN, 15);
        //计算该字体文本的长度
        int wordWidth = getWordWidth(font, text);
        //设置颜色
        graphics.setColor(Color.RED);
        //设置字体
        graphics.setFont(font);
        //写入
        graphics.drawString(text,(width-wordWidth)/2,50);
        graphics.dispose();
        ImageIO.write(bufferedImage, "png", new File("E:\\test\\createimage\\center.png"));
    }

图片结果

 

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值