UIImage添加水印(Logo+文字)及保存本地

总体介绍
把你所需要用到的素材全都渲染到contex中,最后再作为一个整体取出来。

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

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

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

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

应用

由于是UIImage的一些处理,这种需求适合封装为方法


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

    NSUInteger inputWidth = self.size.width;


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

//    开始图片渲染
    [self drawInRect:CGRectMake(0, 0, 100, 40)];

//    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];
    [@"啰里啰嗦一大筐" drawInRect:CGRectMake(targetGhostWidth, wordHigh*1, self.size.width*0.6, wordHigh) withAttributes:dic];

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

    return imageNew;
}

这样写是OK的,要想用logo实际大小可以这样

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

保存到本地

//    Privacy - Photo Library Usage Description  请允许使用相册功能,用于保存截图
//    Privacy - Photo Library Additions Usage Description
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

保存本地是否成功回调

//指定回调方法
-(void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    WeakSelf;
    BOOL issuccess = NO;
    if(!error){
        //    NSLog(@"savesuccess");
        issuccess = YES;
    }else{
        //    NSLog(@"savefailed");
        issuccess = NO;
    }
    NSLog(@"%d", issuccess);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值