这里介绍两种方法:
方法一:添加文字水印,这里说的文字水印是指将开发者定义的文字直接添加到图片上,代码如下:
UIImage *img = [UIImage imageNamed:@"3G_alert.png"]; //需要加水印的图片
CGSize size = self.view.frame.size; //设置上下文(画布)大小
UIGraphicsBeginImageContext(size); //创建一个基于位图的上下文(context),并将其设置为当前上下文
CGContextRef contextRef = UIGraphicsGetCurrentContext(); //获取当前上下文
NSString *title = @"舵手网络"; //需要添加的水印文字
CGContextTranslateCTM(contextRef, 0, self.view.bounds.size.height); //画布的高度
CGContextScaleCTM(contextRef, 1.0, -1.0); //画布翻转
CGContextDrawImage(contextRef, self.view.frame, [img CGImage]); //在上下文种画当前图片
[[UIColor redColor] set]; //上下文种的文字属性
CGContextTranslateCTM(contextRef, 0, self.view.bounds.size.height);
CGContextScaleCTM(contextRef, 1.0, -1.0);
UIFont *font = [UIFont boldSystemFontOfSize:40];
[title drawInRect:CGRectMake(100, 400, 200, 80) withFont:font];
UIImage *res =UIGraphicsGetImageFromCurrentImageContext(); //从当前上下文种获取图片
UIGraphicsEndImageContext(); //移除栈顶的基于当前位图的图形上下文。
NSArray *savePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *p = [savePath objectAtIndex:0];
NSLog(@"%@",p);
NSString *dataFilePath = [p stringByAppendingPathComponent:@"1.png"];
NSData *imageData = UIImagePNGRepresentation(res);
[imageData writeToFile:dataFilePath atomically:YES];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[imageView setImage:res];
[self.view addSubview:imageView];
方法二:添加图片水印,顾名思义,就是两张图片,一张原图,一张水印图片,代码如下:
UIImage *img = [UIImage imageNamed:@"demo.jpg"]; //需要加水印的图片
UIImage *smallImg = [UIImage imageNamed:@"water.png"];
CGSize size = self.view.frame.size; //设置上下文(画布)大小
UIGraphicsBeginImageContext(size); //创建一个基于位图的上下文(context),并将其设置为当前上下文
CGContextRef contextRef = UIGraphicsGetCurrentContext(); //获取当前上下文
CGContextTranslateCTM(contextRef, 0, self.view.bounds.size.height); //画布的高度
CGContextScaleCTM(contextRef, 1.0, -1.0); //画布翻转
CGContextDrawImage(contextRef, self.view.frame, [img CGImage]); //在上下文种画当前图片
CGContextDrawImage(contextRef, CGRectMake(100, 50, 200, 80), [smallImg CGImage]);
UIImage *res = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext(); //移除栈顶的基于当前位图的图形上下文。
NSArray *savePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *p = [savePath objectAtIndex:0];
NSLog(@"%@",p);
NSString *dataFilePath = [p stringByAppendingPathComponent:@"1.png"];
NSData *imageData = UIImageJPEGRepresentation(res, 1.0);
[imageData writeToFile:dataFilePath atomically:YES];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[imageView setImage:res];
[self.view addSubview:imageView];