在做項目的時候我們需要將拍攝的照片做上標記防止圖片被他人盜用,所以這就需要在照片的上面加上水印,以表示此照片的獨一無二。
加水印不是要在上面添加上幾個Label,而是我們要把字畫到圖片上成為一個整體。
提供一個方法 此方法只需要傳遞一個要加水印的圖片和水印的內容就達到效果
1 -(UIImage *)watermarkImage:(UIImage *)img withName:(NSString *)name 2 3 { 4 5 NSString* mark = name; 6 7 int w = img.size.width; 8 9 int h = img.size.height; 10 11 UIGraphicsBeginImageContext(img.size); 12 13 [img drawInRect:CGRectMake(0, 0, w, h)]; 14 15 NSDictionary *attr = @{ 16 17 NSFontAttributeName: [UIFont boldSystemFontOfSize:20], //設置字體 18 19 NSForegroundColorAttributeName : [UIColor redColor] //設置字體顏色 20 21 }; 22 23 [mark drawInRect:CGRectMake(0, 10, 80, 32) withAttributes:attr]; //左上角 24 25 [mark drawInRect:CGRectMake(w - 80, 10, 80, 32) withAttributes:attr]; //右上角 26 27 [mark drawInRect:CGRectMake(w - 80, h - 32 - 10, 80, 32) withAttributes:attr]; //右下角 28 29 [mark drawInRect:CGRectMake(0, h - 32 - 10, 80, 32) withAttributes:attr]; //左下角 30 31 UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext(); 32 33 UIGraphicsEndImageContext(); 34 35 return aimg; 36 37 }
