iOS 合并两张图片(叠加两张图片 重合两张图片)
程序员文章站
2024-03-24 22:53:04
...
最近产品给了一个奇葩的需求,需要把一个活动海报和用户生成的二维码合成一张图片,分享出去,效果如下:
创建一个 UIImageView (黑斜体是关键一行代码)
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 375, 667)];
imgView.image = [self addImage:[self createImageWithString:@“生成二维码规则”] withImage:@"littlesun"];
imgView.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:imgView];
方法实现:
- (UIImage *)addImage:(NSString *)imageName1 withImage:(NSString *)imageName2 {
UIImage *image1 = [UIImage imageNamed:imageName1];
UIImage *image2 = [UIImage imageNamed:imageName2];
UIGraphicsBeginImageContext(image1.size);
[image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];
[image2 drawInRect:CGRectMake((image1.size.width - image2.size.width)/2,(image1.size.height - image2.size.height)/2, image2.size.width, image2.size.height)];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage;
}
// 生成二维码
- (UIImage *)createImageWithString:(NSString *)string{
// 1.实例化二维码滤镜
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2.恢复滤镜的默认属性(因为滤镜可能保存上一次的属性)
[filter setDefaults];
// 3.讲字符串转换为NSData
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
// 4.通过KVO设置滤镜inputMessage数据
[filter setValue:data forKey:@"inputMessage"];
// 5.通过了滤镜输出的图像
CIImage *outputImage = [filter outputImage];
// 6.因为生成的二维码模糊,所以通过createNonInterpolatedUIImageFormCIImage:outputImage来获得高清的二维码图片
UIImage *image = [self getErWeiMaImageFormCIImage:outputImage withSize:200];
return image;
}