為了防止辛苦完成的專案被他人盜用,為圖片加上浮水印是常見做法,用以彰顯圖片的獨一無二。加浮水印並非簡單地在圖片上疊加幾個 Label,而是把文字真正「畫」進圖片,成為一個整體。以下分享兩種實作方式,只需傳入欲加浮水印的圖片與浮水印文字即可達到效果。
第一種方式:在四個角落繪製文字浮水印
- (UIImage *)watermarkImage:(UIImage *)img withName:(NSString *)name {
NSString *mark = name;
int w = img.size.width;
int h = img.size.height;
UIGraphicsBeginImageContext(img.size);
[img drawInRect:CGRectMake(0, 0, w, h)];
NSDictionary *attr = @{
NSFontAttributeName: [UIFont boldSystemFontOfSize:20], // 字體
NSForegroundColorAttributeName: [UIColor redColor] // 字體顏色
};
[mark drawInRect:CGRectMake(0, 0, 100, 30) withAttributes:attr]; // 左上角
[mark drawInRect:CGRectMake(w - 100, 0, 100, 30) withAttributes:attr]; // 右上角
[mark drawInRect:CGRectMake(w - 100, h - 30, 100, 30) withAttributes:attr]; // 右下角
[mark drawInRect:CGRectMake(0, h - 30, 100, 30) withAttributes:attr]; // 左下角
UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return aimg;
}
第二種方式:使用 drawInRect,圖片與文字皆可靈活叠加
這種方式特別適合把一段浮水印圖片(例如 Logo)疊加到指定區域,也可搭配文字使用:
- (UIImage *)imageWithWaterMask:(UIImage *)mask inRect:(CGRect)rect {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
} else {
UIGraphicsBeginImageContext(self.size);
}
[self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)]; // 原圖
[mask drawInRect:rect]; // 浮水印圖
UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newPic;
}
以上兩種方式都能在 iOS 中為圖片加上浮水印。第一種適合在四角繪製文字,第二種則更靈活,可將任意圖片或文字合成到指定位置,可依需求挑選使用。