public static void addTextWatermark(Graphics2D graphics,int srcImgWidth,int srcImgHeight,List textWatermarkList) throws UnsupportedEncodingException {
//-------------------------文字水印 start----------------------------
//根据图片的背景设置水印颜色
graphics.setColor(new Color(255,255,255,128));
//设置字体 画笔字体样式为微软雅黑,加粗,文字大小为60pt
double scale = 1.0;
if(srcImgWidth<srcImgHeight){
scale= (double) srcImgWidth/srcImgHeight;
}
int pix = (int) Math.ceil((double) (srcImgHeight/25)*scale);
Font font = new Font("宋体", Font.BOLD, pix);
graphics.setFont(font);
int x =50;
// 计算水印文字的宽度和高度
FontMetrics fontMetrics = graphics.getFontMetrics();
AtomicInteger count = new AtomicInteger();
textWatermarkList.forEach(e->{
int watermarkWidth = fontMetrics.stringWidth(e);
// 计算水印的行数和行高
int lineCount = (int) Math.ceil((double) (watermarkWidth+pix) / srcImgWidth);
count.addAndGet(lineCount);
});
int lineHeight = fontMetrics.getHeight();
//设置水印的坐标
int y =srcImgHeight - srcImgHeight/30 - count.get() *lineHeight ;
// 绘制水印
int startX = x;
int startY = y;
//画出水印 第一个参数是水印内容,第二个参数是x轴坐标,第三个参数是y轴坐标
for(int i=0;i<textWatermarkList.size();i++) {
String text = textWatermarkList.get(i);
String[] lines = text.split("");
for (int j = 0; j < lines.length; j++) {
if (startX > srcImgWidth-pix) {
startX = x;
startY += lineHeight;
}
String line = lines[j];
graphics.drawString(line, startX, startY);
int textWidth = fontMetrics.stringWidth(line);
startX += textWidth;
}
startY += lineHeight;
startX=x;
}
graphics.dispose();
//-------------------------文字水印 end----------------------------
}