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

  • Post author:
  • Post category:其他



总体介绍


把你所需要用到的素材全都渲染到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);
}



版权声明:本文为iOS_MingXing原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。