一爆雹、生成二維碼
1.首先要導(dǎo)入CoreImage框架
#import <Corelmage/CoreImage.h>
2.創(chuàng)建過濾器
CIFilter*filter = [CIFilterfilterWithName:@"CIQRCodeGenerator"];
3.設(shè)置過濾器為默認模式
[filtersetDefaults];
4.給過濾添加數(shù)據(jù)
NSString*dataString =@"http://www.reibang.com/u/663e6f9b7f55";
NSData*data = [dataStringdataUsingEncoding:NSUTF8StringEncoding];
[filtersetValue:dataforKeyPath:@"inputMessage"];
5.獲取輸出的二維碼
CIImage*outputImage = [filterout putImage];
6.顯示二維碼
self.imageView.image= [self ?createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];
7.為了展示清楚的二維碼圖片需要對outputImage做進一步處理
- (UIImage*)createNonInterpolatedUIImageFormCIImage:(CIImage*)image withSize:(CGFloat) size
{
CGRectextent =CGRectIntegral(image.extent);
CGFloatscale =MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 1.創(chuàng)建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];
}
二抵乓、掃描二維碼
1.創(chuàng)建捕捉會話
AVCaptureSession*session = [[AVCaptureSessionalloc]init];
self.session= session;
?2.添加輸入設(shè)備(數(shù)據(jù)從攝像頭輸入)
AVCaptureDevice*device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput*input = [AVCaptureDeviceInputdeviceInputWithDevice:deviceerror:nil];
[sessionaddInput:input];
?3.添加輸出數(shù)據(jù)(示例對象-->類對象-->元類對象-->根元類對象)
AVCaptureMetadataOutput*output = [[AVCaptureMetadataOutput alloc]init];
[outputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];
[sessionaddOutput:output];
?3.1.設(shè)置輸入元數(shù)據(jù)的類型(類型是二維碼數(shù)據(jù))
[outputsetMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
4.添加掃描圖層
AVCaptureVideoPreviewLayer*layer = [AVCaptureVideoPreviewLayerlayerWithSession:session];
layer.frame=self.view.bounds;
[self.view.layeraddSublayer:layer];
self.layer= layer;
?5.開始掃描
[sessionstartRunning];
6.實現(xiàn)output的回調(diào)方法
//當(dāng)掃描到數(shù)據(jù)時就會執(zhí)行該方法
- (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray*)metadataObjects fromConnection:(AVCaptureConnection*)connection
{
if(metadataObjects.count>0) {
AVMetadataMachineReadableCodeObject*object = [metadataObjects lastObject];
NSLog(@"%@", object.stringValue);
//停止掃描
[self.sessionstopRunning];
//將預(yù)覽圖層移除
[self.layer removeFromSuperlayer];
}else{
NSLog(@"沒有掃描到數(shù)據(jù)");
}
}