在一些應用如微博中,為了防止用戶圖片被盜用,一般會在圖片上加上水印,接下來就給大家分享一個iOS中給圖片加水印的簡單方法.
新建了一個UIImage的類目,在.h中聲明
+ (UIImage *)imageWithimage:(UIImage *)image content:(NSString *)content frame:(CGRect)frame;
.m如下
+ (UIImage *)imageWithimage:(UIImage *)image content:(NSString *)content frame:(CGRect)frame {
// 開啟圖形'上下文'
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
// 繪制原生圖片
[image drawAtPoint:CGPointZero];
// 在原生圖上繪制文字
NSString *str = content;
// 創建文字屬性字典
NSDictionary *dictionary = @{NSForegroundColorAttributeName: [UIColor blackColor], NSFontAttributeName: [UIFont systemFontOfSize:20]};
// 繪制文字屬性
[str drawInRect:frame withAttributes:dictionary];
// 從當前上下文獲取修改后的圖片
UIImage *imageNew = UIGraphicsGetImageFromCurrentImageContext();
// 結束圖形上下文
UIGraphicsEndImageContext();
return imageNew;
}
__但是需要注意的是 drawInRect: withAttributes:方法在iOS7.0以后才能使用, 使用該方法的時候需要先看系統是否合適,也可以在方法中加上判斷.
__
double device = [[UIDevice currentDevice].systemVersion doubleValue];
if (device >= 7.0f) {
// do something
}
之后在VC中導入頭文件, 創建一個imageView
// 調用方法傳入一個image對象,想要添加的文字和文字所在位置
UIImage *image = [UIImage imageWithimage:[UIImage imageNamed:@"3"] content:@"伊利丹" frame: CGRectMake(20, 500, 100, 100)];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
imageView.image = image;
[self.view addSubview:imageView];
效果如下圖,簡單的實現了在圖片上加水印的功能,如果想要改變文字的大小和顏色可以在方法中修改.或者給方法添加一個文字屬性的字典參數.
B9626C0D-A148-4B4F-B8D0-385EB4C87BB5.png