【iOS】生成二维码
作者:互联网
- 直接上干货
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface QRCodeGenerator : NSObject
+(instancetype)shareInstance;
- (UIImage *)creatQRGeneratorWithCenterImage:(UIImage *)centerImage textStr:(NSString*)str;
@end
NS_ASSUME_NONNULL_END
#import "QRCodeGenerator.h"
static QRCodeGenerator * _instance;
@implementation QRCodeGenerator
+ (instancetype)shareInstance{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
_instance = [[self alloc] init];
});
return _instance;
}
- (UIImage *)creatQRGeneratorWithCenterImage:(UIImage *)centerImage textStr:(NSString*)str{
/// 1.创建二维码过滤器
CIFilter * qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
/// 2.设置默认值
[qrFilter setDefaults];
[qrFilter setValue:[str dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];
// 4.获取二维码的图片
CIImage *ciimage = qrFilter.outputImage;
// 放大图片的比例
// ciimage = [ciimage imageByApplyingTransform:CGAffineTransformMakeScale(9, 9)];
/// 返回image
UIImage *newImage = [self createNonInterpolatedUIImageFormCIImage:ciimage withSize:300];
// return [UIImage imageWithCIImage:ciimage] ;
return [self qrGeneratorAddCenterImage:centerImage originalImage:newImage];
}
//--生成高清二维码
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 创建 bitmap
size_t width = CGRectGetWidth(extent) * scale;
size_t height = CGRectGetHeight(extent) * scale;
CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 保存 bitmap 到图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
-(UIImage *)qrGeneratorAddCenterImage:(UIImage *)image originalImage:(UIImage *)originalImage{
/// 开启图形上下文
UIGraphicsBeginImageContext(originalImage.size);
/// 画二维码的图片
[originalImage drawInRect:CGRectMake(0, 0, originalImage.size.width, originalImage.size.height)];
CGFloat meImageW = 50;
CGFloat meImageH = 50;
CGFloat meImageX = (originalImage.size.width - meImageW) * 0.5;
CGFloat meImageY = (originalImage.size.height - meImageH) * 0.5;
/// 画中心图片
[image drawInRect:CGRectMake(meImageX, meImageY, meImageW, meImageH)];
/// 获取图片
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
/// 关闭图形上下文
UIGraphicsEndImageContext();
return finalImage;
}
- 这是生成中间带图片的
请大家关注我的个人公众号
标签:originalImage,iOS,生成,二维码,bitmapRef,extent,UIImage,CGFloat,size 来源: https://blog.csdn.net/Emperor_huanzi/article/details/114319359