d网上有很多关于二维码生成和扫描的资料, 个人感觉都有不必要的复杂, 我们查资料都想着直接可以用是吧, 下面总结了关于二维码生成和扫描的代码,都是本人亲自确认无误的, 可放心使用, 因为怕读者看着乱所以把二维码的生成和扫描分成了两个部分来写.
接下来的代码是纯手工制造 不懂得可以问哦 反正我也不会告诉你的~
@property (nonatomic, strong) UIImage *QRImage;//创建一个image属性
- (void)viewDidLoad {
[super viewDidLoad];
//初始化二维码图片
[self QRImage1];
UIImageView *QRImageView = [[UIImageView alloc] initWithImage:self.QRImage];
QRImageView.frame = CGRectMake((self.view.frame.size.width - 250) / 2, (self.view.frame.size.height - 250) / 2, 250, 250);
[self.view addSubview:QRImageView];
UILabel *tipsLabel = [UILabel new];
tipsLabel.textAlignment = NSTextAlignmentCenter;
tipsLabel.text = @"扫一扫上方二维码,添加好友";
tipsLabel.frame = CGRectMake(0, 100, self.view.frame.size.width, 30);
[self.view addSubview:tipsLabel];
}
#pragma mark - 生产二维码 这里生成的二维码只是一个字符串 具体的效果还是要看实际情况
- (void)QRImage1
{
//string -> data
NSData *stringData = [@"jenny" dataUsingEncoding:NSUTF8StringEncoding];
//使用CIFilter生成二维码QRCode
CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//设置内容和纠错级别
[qrFilter setValue:stringData forKey:@"inputMessage"];
[qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
//二维码的颜色
UIColor *onColor = [UIColor blackColor];
UIColor *offColor = [UIColor whiteColor];
//上色
CIFilter *colorFilter = [CIFilter filterWithName:@"CIFalseColor"
keysAndValues:
@"inputImage",qrFilter.outputImage,
@"inputColor0",[CIColor colorWithCGColor:onColor.CGColor],
@"inputColor1",[CIColor colorWithCGColor:offColor.CGColor],
nil];
CIImage *qrImage = colorFilter.outputImage;
//绘制
CGSize size = CGSizeMake(300, 300);
CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:qrImage fromRect:qrImage.extent];
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
CGContextScaleCTM(context, 1.0, -1.0);//翻转图片
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
UIImage *codeImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(cgImage);
_QRImage = codeImage;
}
<a href="http://www.jianshu.com/p/d31b89003142">二维码扫描链接</a>