UIImage添加水印(Logo+文字)

39 篇文章 0 订阅
6 篇文章 0 订阅

写在前面

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

简单介绍

没有什么逻辑,就是把你所需要用到的素材全都渲染到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)];

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值