1、也就是大家經常用的,一般是圖片的4個角落,基於橫縱坐標來添加。
2、在圖片內基於固定位置,文字始終居中。剛開始我基於第一種場景來根據水印漢字的長度來計算坐標,後來發現方法始終不可靠。現在是先在圖片固定區域(水印區域)畫一個矩形,然後再矩形內添加水印漢字,並使用畫刷保持文字居中。
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(); }
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(); }
和第一種方法比起來,第二種方法更直觀,更短小精悍,只需要在你需要添加水印的圖片上計算好固定坐標然後先畫一個矩形,然後把水印漢字畫在矩形內,這樣不管水印漢字如何變化都可以在圖片固定位置居中。