您的位置:首页 > 产品设计 > UI/UE

UIImage添加水印(Logo+文字)

2017-01-14 18:08 295 查看

写在前面

添加水印是经常遇到的需求了,也算是图像数字处理比较容易的一个环节,网上能搜出好几种解决方案,但作为新手的我还是折腾了好长时间。

简单介绍

没有什么逻辑,就是把你所需要用到的素材全都渲染到contex中,最后再作为一个整体取出来。

// 创建一个bitmap的context
UIGraphicsBeginImageContext();

// 渲染背景图
// 渲染素材logo+文字
// 用的是同一个方法
drawInRect:
. . .

// 取出UIImage
UIImage *imageNew = UIGraphicsGetImageFromCurrentImageContext();

//一些释放操作
UIGraphicsEndImageContext();


应用

由于是UIImage的一些处理,这种需求最合适写进category里面

- (UIImage *)imageWater1:(UIImage *)imageLogo waterString:(NSString *)waterString
{

NSUInteger inputWidth = self.size.width;

// 创建一个bitmap的context
UIGraphicsBeginImageContext(self.size);

//    开始图片渲染
[self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];

//    logo渲染
CGFloat ghostImageAspectRatio = imageLogo.size.width / imageLogo.size.height;
NSInteger targetGhostWidth = inputWidth * 0.3;
[imageLogo drawInRect:CGRectMake(0, 0, targetGhostWidth, targetGhostWidth/ghostImageAspectRatio)];

//    渲染文字
NSUInteger wordHigh = 120;
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:100], NSForegroundColorAttributeName:[UIColor whiteColor], NSParagraphStyleAttributeName:paragraphStyle};
[waterString drawInRect:CGRectMake(targetGhostWidth, 0, self.size.width*0.6, wordHigh) withAttributes:dic];
[@"RNO:0000023034001230" drawInRect:CGRectMake(targetGhostWidth, wordHigh*1, self.size.width*0.6, wordHigh) withAttributes:dic];
[@"GPS:27.34223132,4533.2313324" drawInRect:CGRectMake(targetGhostWidth, wordHigh*2, self.size.width*0.6, wordHigh) withAttributes:dic];
[@"地址:需要您的同意,才能访问相册" drawInRect:CGRectMake(targetGhostWidth, wordHigh*3, self.size.width*0.6, wordHigh) withAttributes:dic];

//    UIImage
UIImage *imageNew = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return imageNew;
}


这样写是OK的,刚开始在渲染logo是这样写的

[imageLogo drawInRect:CGRectMake(0, 0, imageLogo.size.width, imageLogo.size.height)];


渲染出来的 图片特小,因为是位图(bitmap)的关系吧,

要想用logo实际大小可以这样

CGImageRef logoCGImg = [imageLogo CGImage];
CGFloat w = CGImageGetWidth(logoCGImg);
CGFloat h = CGImageGetHeight(logoCGImg);
[imageLogo drawInRect:CGRectMake(0, 0, w, h)];


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uiimage 水印