0x00 步骤
- 先读取两张图片把创建出CGImageRef
- 创建上下文画布
- 把图片依次画在画布指定位置上
- 从上下文中获得合并后的图片
- 关闭上下文
- 释放内存
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 效果图