iOS把两张图片合成一张图片

0x00 步骤

  1. 先读取两张图片把创建出CGImageRef
  2. 创建上下文画布
  3. 把图片依次画在画布指定位置上
  4. 从上下文中获得合并后的图片
  5. 关闭上下文
  6. 释放内存

0x01 代码实现

- (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);
}

0x10 效果图

0.png

1.png

01.png

posted @ 2016-01-28 20:31  LetGo  阅读(1691)  评论(0编辑  收藏  举报