前言
最近在做一个关于二维码的组件,已发布,现总结下。
开发的APP所需支持的最低版本为7.0,最初的方案为扫描使用苹果自带的API实现扫一扫的功能、使用ZXing识别从相册或别人转发的二维码图片。但发现ZXing识别从相册中来的图片性能很差,很多图片识别不了,且耗时较长,遂使用ZBar来实现识别从相册或别人转发的二维码图片。
这个组件重要有三个功能,扫一扫识别二维码图片、长按图片识别二维码图片和生成二维码图片。
扫一扫识别二维码图片
- (void)initCapture {
AVCaptureDevice* inputDevice =
[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[inputDevice lockForConfiguration:nil];
if ([inputDevice hasTorch]) {
inputDevice.torchMode = AVCaptureTorchModeAuto;
}
[inputDevice unlockForConfiguration];
AVCaptureDeviceInput *captureInput =
[AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:nil];
if (!captureInput) {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
UIAlertController *alterVC = [UIAlertController alertControllerWithTitle:@"系统提示" message:@"您已关闭相机使用权限,请至手机“设置->隐私->相机”中打开" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
[alterVC addAction:confirmAction];
[self presentViewController:alterVC animated:YES completion:nil];
} else {
UIAlertController *alterVC = [UIAlertController alertControllerWithTitle:@"系统提示" message:@"未能找到相机设备" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
[alterVC addAction:confirmAction];
[self presentViewController:alterVC animated:YES completion:nil];
}
return;
}
AVCaptureMetadataOutput *captureOutput = [[AVCaptureMetadataOutput alloc] init];
[captureOutput setMetadataObjectsDelegate:self queue:_queue];
self.captureOutput = captureOutput;
self.captureSession = [[AVCaptureSession alloc] init];
[self.captureSession addInput:captureInput];
[self.captureSession addOutput:captureOutput];
CGFloat w = 1920.f;
CGFloat h = 1080.f;
if ([self.captureSession canSetSessionPreset:AVCaptureSessionPreset1920x1080]) {
self.captureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
} else if ([self.captureSession canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
self.captureSession.sessionPreset = AVCaptureSessionPreset1280x720;
w = 1280.f;
h = 720.f;
} else if ([self.captureSession canSetSessionPreset:AVCaptureSessionPreset640x480]) {
self.captureSession.sessionPreset = AVCaptureSessionPreset640x480;
w = 960.f;
h = 540.f;
}
captureOutput.metadataObjectTypes = [captureOutput availableMetadataObjectTypes];
CGRect bounds = [[UIScreen mainScreen] bounds];
if (!self.prevLayer) {
self.prevLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
}
self.prevLaye