話不多說(shuō),直接上代碼
新建了一個(gè)UIImage的類目,在.h中聲明
+ (UIImage *)imageWithimage:(UIImage *)image content:(NSString *)content frame:(CGRect)frame;
.m如下
+ (UIImage *)imageWithimage:(UIImage *)image content:(NSString *)content frame:(CGRect)frame { // 開(kāi)啟圖形'上下文' UIGraphicsBeginImageContextWithOptions(image.size, NO, 0); // 繪制原生圖片 [image drawAtPoint:CGPointZero]; // 在原生圖上繪制文字 NSString *str = content; // 創(chuàng)建文字屬性字典 NSDictionary *dictionary = @{NSForegroundColorAttributeName: [UIColor blackColor], NSFontAttributeName: [UIFont systemFontOfSize:20]}; // 繪制文字屬性 [str drawInRect:frame withAttributes:dictionary]; // 從當(dāng)前上下文獲取修改后的圖片 UIImage *imageNew = UIGraphicsGetImageFromCurrentImageContext(); // 結(jié)束圖形上下文 UIGraphicsEndImageContext(); return imageNew;}
但是需要注意的是 drawInRect: withAttributes:
方法在iOS7.0以后才能使用, 使用該方法的時(shí)候需要先看系統(tǒng)是否合適,也可以在方法中加上判斷.
double device = [[UIDevice currentDevice].systemVersion doubleValue]; if (device >= 7.0f) { // do something }
之后在VC中導(dǎo)入頭文件, 創(chuàng)建一個(gè)imageView
// 調(diào)用方法傳入一個(gè)image對(duì)象,想要添加的文字和文字所在位置 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];
效果如下圖,簡(jiǎn)單的實(shí)現(xiàn)了在圖片上加水印的功能,如果想要改變文字的大小和顏色可以在方法中修改.或者給方法添加一個(gè)文字屬性的字典參數(shù).
以上就是在iOS給圖片加水印的全部?jī)?nèi)容,本文給出了實(shí)例代碼,相信對(duì)大家理解更有幫助,希望能對(duì)大家開(kāi)發(fā)IOS有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選