废话不多说,直接上代码
**先声明几个类**
@interface QRCodeController ()<AVCaptureMetadataOutputObjectsDelegate>
@property(nonatomic,strong)AVCaptureDeviceInput *input;
@property(nonatomic,strong)AVCaptureMetadataOutput *output;
@property(nonatomic,strong)AVCaptureSession *session;
@property(nonatomic,strong)AVCaptureVideoPreviewLayer *prelayer;
@end
- (void)instanceDevice{
line_tag = 1872637;
//获取摄像设备
AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//创建输入流
AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
//创建输出流
AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
//设置扫描区域,很简单被很多人忽略的属性,注意这是是按比例计算的!!!
CGSize size = self.view.bounds.size;
CGRect cropRect = CGRectMake(40, 180, 240, 240);
output.rectOfInterest = CGRectMake(cropRect.origin.y/size.height,
cropRect.origin.x/size.width,
cropRect.size.height/size.height,
cropRect.size.width/size.width);
//设置代理 在主线程里刷新
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//初始化链接对象
self.session = [[AVCaptureSession alloc]init];
//高质量采集率
[self.session setSessionPreset:AVCaptureSessionPresetHigh];
if (input) {
[self.session addInput:input];
}
if (output) {
[self.session addOutput:output];
//设置扫码支持的编码格式(如下设置条形码和二维码兼容)
NSMutableArray *a = [[NSMutableArray alloc] init];
if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode]) {
[a addObject:AVMet