场景一
也就是大家经常用的,一般是图片的4个角落,基于横纵坐标来添加。
效果如下:

添加水印方法
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
static void addwatermarktext(graphics picture,int fontsize, string _watermarktext, string _watermarkposition, int _width, int _height)
{
int[] sizes = new int[] {32, 14, 12, 10, 8, 6, 4 };
font crfont = null;
sizef crsize = new sizef();
crfont = new font("微软雅黑", fontsize, fontstyle.bold);
crsize = picture.measurestring(_watermarktext, crfont);
float xpos = 0;
float ypos = 0;
color color =color.firebrick;
switch (_watermarkposition)
{
case "wm_top_left":
xpos = ((float)_width * (float).01) + (crsize.width / 2);
ypos = (float)_height * (float).01;
break;
case "wm_top_right":
xpos = ((float)_width * (float).99) - (crsize.width / 2);
ypos = (float)_height * (float).01;
break;
case "wm_bottom_right":
xpos = ((float)_width * (float).99) - (crsize.width / 2);
ypos = ((float)_height * (float).99) - crsize.height;
break;
case "wm_bottom_left":
xpos = ((float)_width * (float).01) + (crsize.width / 2);
ypos = ((float)_height * (float).99) - crsize.height;
break;
}
stringformat strformat = new stringformat();
strformat.alignment = stringalignment.center;
solidbrush semitransbrush2 = new solidbrush(color.fromargb(153, 0, 0, 0));//加阴影
picture.drawstring(_watermarktext, crfont, semitransbrush2, xpos + 1, ypos + 1, strformat);
solidbrush semitransbrush = new solidbrush(color); //添加水印
picture.drawstring(_watermarktext, crfont, semitransbrush, xpos, ypos, strformat);
semitransbrush2.dispose();
semitransbrush.dispose();
}
|
场景二
在图片内基于固定位置,文字始终居中。刚开始我基于第一种场景来根据水印汉字的长度来计算坐标,后来发现方法始终不可靠。现在是先在图片固定区域(水印区域)画一个矩形,然后再矩形内添加水印汉字,并使用画刷保持文字居中。
效果图如下

添加水印的方法
?| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
static void addwatermarktext(graphics picture,string type, int fontsize, string _watermarktext)
{
//1、先画矩形
rectanglef drawrect;
color color;
if (type == "top")
{
drawrect = new rectanglef(73, 135, 450, 64);
color = color.fromargb(255, 255, 255);
}
else
{
drawrect = new rectanglef(194, 245, 250, 39);
color = color.fromargb(244, 226, 38);
}
//2、在基于矩形画水印文字
font crfont = null;
stringformat strformat = new stringformat();
strformat.alignment = stringalignment.center;
crfont = new font("微软雅黑", fontsize, fontstyle.bold);
solidbrush semitransbrush = new solidbrush(color); //添加水印
picture.drawstring(_watermarktext, crfont, semitransbrush, drawrect, strformat);
semitransbrush.dispose();
}
|
总结
和第一种方法比起来,第二种方法更直观,更短小精悍,只需要在你需要添加水印的图片上计算好固定坐标然后先画一个矩形,然后把水印汉字画在矩形内,这样不管水印汉字如何变化都可以在图片固定位置居中。以上就是这篇文章的全部内容,希望能对大家的学习或者工作带来一定的帮助。








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。