objective-c二維碼的掃碼與生成 掃描二維碼 生成二維碼
1.掃描二維碼獲取輸出設備(以後是攝像頭)
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
依據輸出設備獲取輸出對象
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
創立輸入對象
AVCaptureMetadataOutput *output = [AVCaptureMetadataOutput new];
設置代理監聽對象輸入的數據,在主線程回調
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
創立會話
AVCaptureSession *session = [AVCaptureSession new];
//完成高質量的輸入和攝像,默許值為AVCaptureSessionPresetHigh,可以不寫
[session setSessionPreset:AVCaptureSessionPresetHigh];
添加輸出輸入到會話中(判別session能否已滿)
if ([session canAddInput:input]) {
[session addInput:input];
}
if ([session canAddOutput:output]) {
[session addOutput:output];
}
設置輸入對象的輸入什麼樣的數據(二維碼、條碼)
output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode39Mod43Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeUPCECode,AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeAztecCode];
創立預覽圖層
AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeaspectFill];
previewLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:previewLayer atIndex:0];
設置無效掃描區域
CGRect rect = CGRectMake(0.1,0.1,0.8,0.8);
output.rectOfInterest = rect;
設置周邊空白區域(兩頭掃描區域通明度比其他中央低)
UIView *maskView = [[UIView alloc] initWithFrame:self.view.bounds];
maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4f];
[self.view addSubview:maskView];
UIBezierPath *rectPath = [UIBezierPath bezierPathWithRect:self.view.bounds];
[rectPath appendPath:[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(20.0f, 20.0f, 200.0f, 200.0f) cornerRadius:1] bezierPathByReversingPath]];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = rectPath.CGPath;
maskView.layer.mask = shapeLayer;
掃描成功後的回調
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
if (metadataObjects.count > 0) {
//取出掃描到得數據
AVMetadataMachineReadableCodeObject *obj = [metadataObjects lastObject];
if (obj) {
NSLog(@"result = %@",[obj stringValue]);
}
}
}
2.生成二維碼
二維碼濾鏡
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
設置濾鏡的默許屬性
[filter setDefaults];
將字符串轉成二進制數據
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
經過KVO設置濾鏡inputmessage數據
[filter setValue:data forKey:@"inputMessage"];
獲取濾鏡輸入的圖片
CIImage *outputImage = [filter outputImage];
//轉成UIImage前往
UIImage *image = [UIImage imageWithCIImage:outputImage];
【iOS掃描二維碼與生成二維碼】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!