最近有一个需求是需要将分享链接做成二维码配合宣传海报分发出去
这里遇到一个知识点就是如何转换成二维码,其实在iOS中其实已经提供了CIFilter 提供转换还是很方便的。
+ (UIImage *)createQRCode:(NSString *)code size:(CGSize)size quality:(RainQRCodeQuality)quality {
if (!code) {
return nil;
}
NSData *data = [code dataUsingEncoding:NSUTF8StringEncoding];
NSString *qiInputCorrection = @"Q";
switch (quality) {
case RainQRCodeQualityL:
qiInputCorrection = @"L";
break;
case RainQRCodeQualityM:
qiInputCorrection = @"M";
break;
case RainQRCodeQualityQ:
qiInputCorrection = @"Q";
break;
case RainQRCodeQualityH:
qiInputCorrection = @"H";
break;
}
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator" withInputParameters:@{@"inputMessage": data, @"inputCorrectionLevel": qiInputCorrection}];
UIImage *QRImage = [self scaleImage:filter.outputImage toSize:size];
return QRImage;
}
需要说明的是:
inputCorrectionLevel对应四个容错率(如下),容错率越大,允许二维码污损的面积越大;
static NSString *QiInputCorrectionLevelL = @"L";//!< L: 7%
static NSString *QiInputCorrectionLevelM = @"M";//!< M: 15%
static NSString *QiInputCorrectionLevelQ = @"Q";//!< Q: 25%
static NSString *QiInputCorrectionLevelH = @"H";//!< H: 30%
+ (UIImage *)scaleImage:(CIImage *)image toSize:(CGSize)size {
CGRect integralRect = image.extent;
CGImageRef imageRef = [[CIContext context] createCGImage:image fromRect:integralRect];
CGFloat sideScale = fminf(size.width / integralRect.size.width, size.width / integralRect.size.height) * [UIScreen mainScreen].scale;// 计算需要缩放的比例
size_t contentRefWidth = ceilf(integralRect.size.width * sideScale);
size_t contentRefHeight = ceilf(integralRect.size.height * sideScale);
CGContextRef contextRef = CGBitmapContextCreate(nil, contentRefWidth, contentRefHeight, 8, 0, CGColorSpaceCreateDeviceGray(), (CGBitmapInfo)kCGImageAlphaNone);
CGContextSetInterpolationQuality(contextRef, kCGInterpolationNone);
CGContextScaleCTM(contextRef, sideScale, sideScale);
CGContextDrawImage(contextRef, integralRect, imageRef);
CGImageRef sacledImageRef = CGBitmapContextCreateImage(contextRef);
CGContextRelease(contextRef);
CGImageRelease(imageRef);
UIImage *scaleImage = [UIImage imageWithCGImage:sacledImageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
return scaleImage;
}
其实在scaleImage这个方法里才是重头戏,但是迫于时间压力后面在看具体内容是什么
参考文章QiShare团队的文章