以下是合成的步骤:
- 先读取两张图片把创建出CGImageRef
- 创建上下文画布
- 把图片依次画在画布指定位置上
- 从上下文中获得合并后的图片
- 关闭上下文
- 释放内存
两张图片合成:- (void)composeImg {
UIImage *img = [UIImage imageNamed:@"0.png"];
CGImageRef imgRef = img.CGImage;
CGFloat w = CGImageGetWidth(imgRef);
CGFloat h = CGImageGetHeight(imgRef);
UIImage *img1 = [UIImage imageNamed:@"1.png"];
CGImageRef imgRef1 = img1.CGImage;
CGFloat w1 = CGImageGetWidth(imgRef1);
CGFloat h1 = CGImageGetHeight(imgRef1);
UIGraphicsBeginImageContext(CGSizeMake(w1, h1));
[img1 drawInRect:CGRectMake(0, 0, w1, h1)];
[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函数
如果觉得对你有用,可以微信随意打赏