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"));
}
图片结果