二维码生成步骤:
1.导入CoreImage框架
2.通过滤镜CIFilter生成二维码
示例代码:
1.创建过滤器
CIFilter*filter = [CIFilterfilterWithName:@"CIQRCodeGenerator"];
2.恢复默认
[filtersetDefaults];
3.给过滤器添加数据(正则表达式/账号和密码)
NSString*dataString =@"http://www.520it.com";
NSData*data = [dataStringdataUsingEncoding:NSUTF8StringEncoding];
[filtersetValue:dataforKeyPath:@"inputMessage"];
4.获取输出的二维码
CIImage*outputImage = [filteroutputImage];
5.显示二维码
self.imageView.image= [selfcreateNonInterpolatedUIImageFormCIImage:outputImagewithSize:200];
在第五步显示二维码的时候用了一个自己封装的方法(解决二维码图片不清晰)
具体方法如下:
/**
*根据CIImage生成指定大小的UIImage
*
* @param image CIImage
* @param size图片宽度
*/
- (UIImage*)createNonInterpolatedUIImageFormCIImage:(CIImage*)image withSize:(CGFloat) size
{
CGRectextent =CGRectIntegral(image.extent);
CGFloatscale =MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 1.创建bitmap;
size_twidth =CGRectGetWidth(extent) * scale;
size_theight =CGRectGetHeight(extent) * scale;
CGColorSpaceRefcs =CGColorSpaceCreateDeviceGray();
CGContextRefbitmapRef =CGBitmapContextCreate(nil, width, height,8,0, cs, (CGBitmapInfo)kCGImageAlphaNone);
CIContext*context = [CIContextcontextWithOptions:nil];
CGImageRefbitmapImage = [contextcreateCGImage:imagefromRect:extent];
CGContextSetInterpolationQuality(bitmapRef,kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 2.保存bitmap到图片
CGImageRefscaledImage =CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return[UIImageimageWithCGImage:scaledImage];
}
以上完整生成二维码的代码详见gitHub:https://github.com/KimsLeo/joker2.git
二维码扫描
// 1.创建捕捉会话
AVCaptureSession*session = [[AVCaptureSessionalloc]init];
self.session= session;
// 2.添加输入设备(数据从摄像头输入)
AVCaptureDevice*device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput*input = [AVCaptureDeviceInputdeviceInputWithDevice:deviceerror:nil];
[sessionaddInput:input];
// 3.添加输出数据(示例对象-->类对象-->元类对象-->根元类对象)
AVCaptureMetadataOutput*output = [[AVCaptureMetadataOutputalloc]init];
[outputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];
[sessionaddOutput:output];
// 3.1.设置输入元数据的类型(类型是二维码数据)
[outputsetMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
// 4.添加扫描图层
AVCaptureVideoPreviewLayer*layer = [AVCaptureVideoPreviewLayerlayerWithSession:session];
layer.frame=self.view.bounds;
[self.view.layeraddSublayer:layer];
self.layer= layer;
// 5.开始扫描
[sessionstartRunning];
扫描数据以后的方法回调(捕捉扫描数据):
#pragma mark -实现output的回调方法
//当扫描到数据时就会执行该方法
- (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray*)metadataObjects fromConnection:(AVCaptureConnection*)connection
{
if(metadataObjects.count>0) {
AVMetadataMachineReadableCodeObject*object = [metadataObjectslastObject];
NSLog(@"%@", object.stringValue);
//停止扫描
[self.sessionstopRunning];
//将预览图层移除
[self.layerremoveFromSuperlayer];
}else{
NSLog(@"没有扫描到数据");
}
}
扫描二维码的完整代码详见gitHub:https://github.com/KimsLeo/joker2.git