实现思路:
- 开启一个和原始图片一样的图片上下文.
- 把原始图片先绘制到图片上下文.
- 再把要添加的水印(文字,logo)等绘制到图片上下文. 最后从上下文中取出一张图片.
- 关闭图片上下文.
代码实现:
// 加载图片
UIImage *image = [UIImage imageNamed:@"小黄人"];
/**创建一个位图上下文.
size:要开启一个多大的图片上下文.
opaque:不透明,当为YES为不透明, 为NO的时候透明,
scale:是否需要缩放.
*/
UIGraphicsBeginImageContextWithOptions(image.size, YES, 0.0);
// CGContextRef ctx = UIGraphicsGetCurrentContext();
//kCGBlendModeNormal:默认的模式。前景图会覆盖背景图
[image drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:1.0];
NSString *str = @"丹丹是个胆小鬼";
NSDictionary *dict = @{
NSFontAttributeName:[UIFont systemFontOfSize:30],
NSForegroundColorAttributeName:[UIColor orangeColor]
};
// 添加水印的位置
[str drawAtPoint:CGPointMake(image.size.width - 200, image.size.height-100) withAttributes:dict];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 从当前上下文生成一张图片
NSData *newData = UIImagePNGRepresentation(newImage);
// 把图片输出到电脑桌面
[newData writeToFile:@"/Users/sssGKC/Desktop/mypng.png" atomically:YES];
self.imageView.image = newImage;
网友评论