欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS图片拼接,图片文字合成总结

程序员文章站 2022-04-02 23:49:01
iOS图片拼接,图片文字合成总结 一、注意事项:项目报错,图片模糊,内存问题,离屏渲染 二、以下是合成的步骤: 1、先读取两张图片把创建出CGImageRef 2、创建上下...

iOS图片拼接,图片文字合成总结

一、注意事项:项目报错,图片模糊,内存问题,离屏渲染

二、以下是合成的步骤:

1、先读取两张图片把创建出CGImageRef

2、创建上下文画布

3、把图片依次画在画布指定位置上

4、从上下文中获得合并后的图片

5、关闭上下文

6、释放内存

7、两张图片合成:

(void)composeImg {
    UIImage *img = [UIImage imageNamed:@"0.png"];
    CGImageRef imgRef = img.CGImage;
    CGFloat w = CGImageGetWidth(imgRef);
    CGFloat h = CGImageGetHeight(imgRef);

    //以1.png的图大小为底图
    UIImage *img1 = [UIImage imageNamed:@"1.png"];
    CGImageRef imgRef1 = img1.CGImage;
    CGFloat w1 = CGImageGetWidth(imgRef1);
    CGFloat h1 = CGImageGetHeight(imgRef1);

    //以1.png的图大小为画布创建上下文
    UIGraphicsBeginImageContext(CGSizeMake(w1, h1));
    [img1 drawInRect:CGRectMake(0, 0, w1, h1)];//先把1.png 画到上下文中
    [img drawInRect:CGRectMake(100, 100, w, h)];//再把小图放在上下文中
    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();//从当前上下文中获得最终图片
    UIGraphicsEndImageContext();//关闭上下文

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"01.png"];
    [UIImagePNGRepresentation(resultImg) writeToFile:filePath atomically:YES];//保存图片到沙盒

    CGImageRelease(imgRef);
    CGImageRelease(imgRef1);
}

图片与文字合成:

(UIImage *)CSImage:(UIImage *)img AddText:(NSString *)text
{
     
    UIImageView *view = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
    view.image = img;
     
     
 
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];
 
    [label setNumberOfLines:0];
    label.lineBreakMode = UILineBreakModeWordWrap;
 
    NSString *s = text;
    UIFont *font = [UIFont fontWithName:@"Arial" size:12];
 
    CGSize size = CGSizeMake(320,2000);
 
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    label.frame = CGRectMake(0,0, labelsize.width, labelsize.height);
     
    [view addSubview:label];
 
    return [self convertViewToImage:view];
}
 
-(UIImage*)convertViewToImage:(UIView*)v
{
    CGSize s = v.bounds.size;
     
 
     
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
     
    CGContextRef context = UIGraphicsGetCurrentContext();
     
    [v.layer renderInContext:context];
     
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
     
    v.layer.contents = nil; 
    return image; 
     
}

图片模糊问题,解决方法:1本身图片有问题,2图片压缩的太狠了,3使用WithOptions函数