您的位置:首页 > 移动开发 > IOS开发

[iOS]分享一段用系统API生产二维码的代码

2016-02-23 11:04 423 查看
@interface NSString (LyQR)

/**
*  根据字符串生产二维码图片 【注意:如果要放大显示,请将UIImageView对象的layer.magnificationFilter = kCAFilterNearest; 修改放大算法的选择,保证图片不会模糊】
*
*  @param foregroundColor 二维码图片的颜色【nil是黑色】
*  @param backgroundColor 二维码图片的背景颜色【nil是白色】
*
*  @return 二维码图片
*/
- (UIImage *)ly_QRImageWithForegroundColor:(UIColor *)foregroundColor backgroundColor:(UIColor *)backgroundColor;
- (UIImage *)ly_QRImage;

@end

@implementation NSString (LyQR)

- (UIImage *)ly_QRImage; {
return [self ly_QRImageWithForegroundColor:nil backgroundColor:nil];
}

- (UIImage *)ly_QRImageWithForegroundColor:(UIColor *)foregroundColor backgroundColor:(UIColor *)backgroundColor; {

CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[qrFilter setValue:[self dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];
[qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];

CIImage *ciImage = qrFilter.outputImage;
if (foregroundColor != nil || backgroundColor != nil) {
CIFilter *colorFilter = [CIFilter filterWithName:@"CIFalseColor"];
[colorFilter setValue:ciImage forKey:@"inputImage"];
if (foregroundColor != nil) {
[colorFilter setValue: [CIColor colorWithCGColor:foregroundColor.CGColor] forKey:@"inputColor0"];
}
if (backgroundColor != nil) {
[colorFilter setValue: [CIColor colorWithCGColor:backgroundColor.CGColor] forKey:@"inputColor1"];
}
ciImage = [colorFilter outputImage];
}

// 生产图片
CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:ciImage fromRect:ciImage.extent];

UIGraphicsBeginImageContext(ciImage.extent.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
CGContextScaleCTM(context, 1.0, -1.0);  // 翻转,否则是生产的二维码是个倒的
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGImageRelease(cgImage);

return image;
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息