1.制作扫描框
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#define ScannerHeight 200 #define ScannerWidth 200 #define SCREENWIDTH [UIScreen mainScreen].bounds.size.width #define AppScreenheight ([UIScreen mainScreen].bounds.size.height-64) #import "YscanView.h" @implementation YscanView -(id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self setOverlayPickerView]; self.backgroundColor = [UIColor clearColor]; } return self; } - (void)setOverlayPickerView { CGFloat viewalpha =0.4; UIColor *mycolor=[UIColor blackColor]; UIView* upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,SCREENWIDTH,AppScreenheight/2-ScannerHeight/2-20)]; upView.alpha = viewalpha; upView.backgroundColor = mycolor; [self addSubview:upView]; UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0,upView.frame.size.height,SCREENWIDTH/2-ScannerWidth/2,ScannerHeight)]; leftView.alpha = viewalpha; leftView.backgroundColor = mycolor; [self addSubview:leftView]; UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(leftView.frame.size.width+ScannerWidth,leftView.frame.origin.y,SCREENWIDTH-(leftView.frame.size.width+ScannerWidth), ScannerHeight)]; rightView.alpha = viewalpha; rightView.backgroundColor = mycolor; [self addSubview:rightView]; CGFloat downViewY = ScannerHeight+upView.frame.size.height; CGFloat downViewH = AppScreenheight-(ScannerHeight+upView.frame.size.height); UIView * downView = [[UIView alloc] initWithFrame:CGRectMake(0,downViewY,SCREENWIDTH,downViewH)]; downView.alpha = viewalpha; downView.backgroundColor = mycolor; [self addSubview:downView]; imageView=[[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftView.frame), upView.frame.size.height, ScannerWidth, ScannerWidth)]; imageView.image=[UIImage imageNamed:@"SaoMiaoKuang"]; imageView.layer.opacity=1; imageView.backgroundColor=[UIColor clearColor]; [self addSubview:imageView]; CGRect qrCodeLineframe=CGRectZero; qrCodeLineframe=CGRectMake(CGRectGetMinX(imageView.frame),CGRectGetMinY(imageView.frame),ScannerWidth,11); qrCodeLine = [[UIImageView alloc] initWithFrame:qrCodeLineframe]; qrCodeLine.image=[UIImage imageNamed:@"SaoMiaoLine"]; [self addSubview:qrCodeLine]; UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(imageView.frame)-5,imageView.frame.size.height+imageView.frame.origin.y+20,ScannerWidth+10, 20)]; label.text=@"对准二维码到框内即可自动扫描"; label.font=[UIFont systemFontOfSize:15]; label.backgroundColor=[UIColor clearColor]; [self addSubview:label]; } #pragma mark ==== -(void) stopTimer { if ([_mytimer isValid]==YES) { [_mytimer invalidate]; _mytimer =nil; } } - (void)createTimer { _mytimer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(moveUpAndDownLine) userInfo:nil repeats:YES]; } - (void)moveUpAndDownLine { CGFloat Y = qrCodeLine.frame.origin.y; CGFloat qrCodeLineX =qrCodeLine.frame.origin.x; if (CGRectGetMinY(imageView.frame)==Y){ [UIView beginAnimations:@"asa" context:nil]; [UIView setAnimationDuration:1]; qrCodeLine.frame=CGRectMake(qrCodeLineX,CGRectGetMaxY(imageView.frame)-11,ScannerWidth,11); [UIView commitAnimations]; }else if(CGRectGetMaxY(imageView.frame)-11==Y){ [UIView beginAnimations:@"asa" context:nil]; [UIView setAnimationDuration:1]; qrCodeLine.frame=CGRectMake(qrCodeLineX,CGRectGetMinY(imageView.frame),ScannerWidth,11); [UIView commitAnimations]; } } @end
2.判断iOS版本
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
if ([[UIDevice currentDevice].systemVersion integerValue]>=7.0) { YsanViewController * rt = [[YsanViewController alloc]init]; rt.hidesBottomBarWhenPushed=YES; self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil]; [self.navigationController pushViewController:rt animated:YES]; } else { YzbarVC * myzbar =[[YzbarVC alloc]init]; myzbar.showsZBarControls = NO; myzbar.hidesBottomBarWhenPushed=YES; [self.navigationController pushViewController:myzbar animated:YES]; }
3.导入第三方库(ZBarSDK),并导入#import "ZBarReaderController.h"
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#import "YsanViewController.h" #import "WeizhanBrower.h" #import "ZBarReaderController.h" @interface YsanViewController ()<ZBarReaderDelegate,AVCaptureMetadataOutputObjectsDelegate> @property (nonatomic,strong)AVCaptureDevice * capturedevice; @property (strong,nonatomic)AVCaptureDeviceInput * deviceinput; @property (strong,nonatomic)AVCaptureMetadataOutput * metadataoutput; @property (strong,nonatomic)AVCaptureSession * capturesession; @property (strong,nonatomic)AVCaptureVideoPreviewLayer * capturepreview; @property (strong,nonatomic)UIView * viewPreview; @property (strong,nonatomic)YscanView * ysanview; @property (strong,nonatomic) WeizhanBrower * weizhanbrower; @end @implementation YsanViewController @synthesize ysanview; -(void)loadView { [super loadView]; UIButton * bac =[UIButton buttonWithType:UIButtonTypeSystem]; bac.frame=CGRectMake(0, 4, 42, 40); [bac setTitle:@"相册" forState:UIControlStateNormal]; [bac addTarget:self action:@selector(pickImageFromAlbum) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem * bacitem =[[UIBarButtonItem alloc]initWithCustomView:bac]; self.navigationItem.rightBarButtonItem=bacitem; self.view.backgroundColor=[UIColor blackColor]; ysanview =[[YscanView alloc]initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].applicationFrame.size.width, [UIScreen mainScreen].applicationFrame.size.height)]; [self initScanUI]; [self.view addSubview:ysanview]; } - (void)viewDidLoad { [super viewDidLoad]; } -(void)pickImageFromAlbum { ZBarReaderController *reader = [ZBarReaderController new]; reader.readerDelegate = self; reader.showsHelpOnFail = NO; reader.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; ZBarImageScanner *myscanner = reader.scanner; [myscanner setSymbology: ZBAR_QRCODE config: ZBAR_CFG_ENABLE to: 1]; [self presentViewController:reader animated:YES completion:nil]; } -(void)viewWillAppear:(BOOL)animated { [_capturesession startRunning]; [ysanview createTimer]; } -(void)viewWillDisappear:(BOOL)animated { self.view=nil; [self stopQRCodeReading]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } -(void)initScanUI { _capturedevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; NSError *error = nil; _deviceinput =[AVCaptureDeviceInput deviceInputWithDevice:_capturedevice error:&error]; if (error) { NSLog(@"-%@", error.localizedDescription); return; } _metadataoutput=[[AVCaptureMetadataOutput alloc]init]; [_metadataoutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; _capturesession=[[AVCaptureSession alloc]init]; if ([self checkDevice:@"iPad"]) { [_capturesession setSessionPreset:AVCaptureSessionPreset640x480]; } else { [_capturesession setSessionPreset:AVCaptureSessionPresetHigh]; } [_capturesession addInput:_deviceinput]; [_capturesession addOutput:_metadataoutput]; _metadataoutput.metadataObjectTypes =@[AVMetadataObjectTypeQRCode]; _capturepreview =[[AVCaptureVideoPreviewLayer alloc]initWithSession:_capturesession]; [_capturepreview setVideoGravity:AVLayerVideoGravityResizeAspectFill]; _capturepreview.frame =self.view.layer.bounds; [self.view.layer insertSublayer:_capturepreview atIndex:0]; } -(BOOL)checkDevice:(NSString*)name { NSString* deviceType = [UIDevice currentDevice].model; NSRange range = [deviceType rangeOfString:name]; return range.location != NSNotFound; } - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection { NSString *stringValue; if ([metadataObjects count] >0) { [self stopQRCodeReading]; AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0]; stringValue = metadataObject.stringValue; [self CreatWeizhanBrower:stringValue]; self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil]; [self.navigationController pushViewController:_weizhanbrower animated:YES]; } } -(void)CreatWeizhanBrower:(NSString *)Url { _weizhanbrower =[[WeizhanBrower alloc]init]; _weizhanbrower.URLstr=Url; } - (void)stopQRCodeReading { [_capturesession stopRunning]; [_capturepreview removeFromSuperlayer]; [ysanview stopTimer]; [ysanview removeFromSuperview]; } #pragma mark ===imagePickerDelegate -(void)imagePickerController:(UIImagePickerController*)reader didFinishPickingMediaWithInfo:(NSDictionary*) info { id<NSFastEnumeration> results =[info objectForKey: ZBarReaderControllerResults]; ZBarSymbol *symbol = nil; for(symbol in results) break; [reader dismissViewControllerAnimated:NO completion:nil]; [self CreatWeizhanBrower:symbol.data]; self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil]; [self.navigationController pushViewController:_weizhanbrower animated:YES]; } -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:nil]; } #pragma mark ==== ZBarReaderControllerDelegate - (void)readerControllerDidFailToRead: (ZBarReaderController*)reader withRetry: (BOOL)retry { if(retry) { UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:@"您选择的二维码不正确,请重新选择" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil]; [alert show]; if(![self.parentViewController isBeingDismissed]){ [self dismissViewControllerAnimated:YES completion:nil]; } } else { [reader dismissViewControllerAnimated:YES completion:nil]; } } @end
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#import "YzbarVC.h" #import <AVFoundation/AVFoundation.h> @implementation YzbarVC -(void)viewDidLoad { [super viewDidLoad]; [self CreatzBarVC]; } -(void)CreatzBarVC { self.readerDelegate = self; self.wantsFullScreenLayout=NO; self.supportedOrientationsMask = ZBarOrientationMaskAll; ZBarImageScanner *myscanner = self.scanner; self.videoQuality=UIImagePickerControllerQualityTypeHigh; [myscanner setSymbology: ZBAR_I25 config: ZBAR_CFG_ENABLE to: 0]; UIButton * bac =[UIButton buttonWithType:UIButtonTypeSystem]; bac.frame=CGRectMake(0, 4, 42, 40); [bac setTitle:@"相册" forState:UIControlStateNormal]; [bac addTarget:self action:@selector(pickImageFromAlbum) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem * bacitem =[[UIBarButtonItem alloc]initWithCustomView:bac]; self.navigationItem.rightBarButtonItem=bacitem; ysanview =[[YscanView alloc]initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].applicationFrame.size.width, [UIScreen mainScreen].applicationFrame.size.height)]; [self.view addSubview:ysanview]; [ysanview createTimer]; } -(void)pickImageFromAlbum { ZBarReaderController *reader = [ZBarReaderController new]; reader.readerDelegate = self; reader.showsHelpOnFail = NO; reader.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; ZBarImageScanner *myscanner = reader.scanner; [myscanner setSymbology: ZBAR_QRCODE config: ZBAR_CFG_ENABLE to: 1]; [self presentViewController:reader animated:YES completion:nil]; } -(void)loadMultifunctionView:(UIView *)view { UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom]; //[cancelButton setFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height-100,SCREENWIDTH, 40)]; [cancelButton setTitle:@"我的二维码" forState:UIControlStateNormal]; [cancelButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)]; [cancelButton.titleLabel setFont:[UIFont boldSystemFontOfSize:20]]; // [cancelButton addTarget:self action:@selector(dismissOverlayView:)forControlEvents:UIControlEventTouchUpInside]; cancelButton.backgroundColor=[UIColor clearColor]; [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [view addSubview:cancelButton]; } -(void)CreatWeizhanBrower:(ZBarSymbol *)symbol { weizhanbrower =[[WeizhanBrower alloc]init]; weizhanbrower.URLstr=symbol.data; } #pragma mark ===imagePickerDelegate -(void)imagePickerController:(UIImagePickerController*)reader didFinishPickingMediaWithInfo:(NSDictionary*) info { id<NSFastEnumeration> results =[info objectForKey: ZBarReaderControllerResults]; ZBarSymbol *symbol = nil; for(symbol in results) break; [reader dismissViewControllerAnimated:NO completion:nil]; [self CreatWeizhanBrower:symbol]; self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil]; [self.navigationController pushViewController:weizhanbrower animated:YES]; } -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:nil]; } #pragma mark ==== ZBarReaderControllerDelegate - (void)readerControllerDidFailToRead: (ZBarReaderController*)reader withRetry: (BOOL)retry { if(retry) { UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:@"您选择的二维码不正确,请重新选择" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil]; [alert show]; if(![self.parentViewController isBeingDismissed]){ [self dismissViewControllerAnimated:YES completion:nil]; } } else { [reader dismissViewControllerAnimated:YES completion:nil]; } } @end