? ? ? 對于現(xiàn)在的App應(yīng)用來說,掃描二維碼和條形碼這個(gè)功能是再正常不過的一個(gè)功能了,在早期開發(fā)這些功能的時(shí)候,大家或多或少的都接觸過ZXing和ZBar這類的第三方庫疹蛉,但從iOS7以后,蘋果就給我們提供了系統(tǒng)原生的API來支持我們掃描獲取二維碼力麸,ZXing和ZBar在使用中或多或少有不盡如人意的地方可款,再之停止更新很久了,所以今天我們就來聊聊如何用系統(tǒng)原生的方法掃描獲取二維碼末盔,強(qiáng)大的AVFoundation框架給我們提供了掃描私有方法和代理方法。
? ? ?首先獲取流媒體信息我們需要AVCaptureSession對象來管理輸入流和輸出流座慰,AVCaptureVideoPreviewLayer對象來顯示信息陨舱,基本流程如下圖所示
AVCaptureSession管理輸入(AVCaptureInput)和輸出(AVCaptureOutput)流,包含開啟和停止會(huì)話方法版仔。
AVCaptureDeviceInput是AVCaptureInput的子類,可以作為輸入捕獲會(huì)話癣朗,用AVCaptureDevice實(shí)例初始化。
AVCaptureDevice代表了物理捕獲設(shè)備如:攝像機(jī)浅浮。用于配置等底層硬件設(shè)置相機(jī)的自動(dòng)對焦模式独榴。
AVCaptureMetadataOutput是AVCaptureOutput的子類,處理輸出捕獲會(huì)話兰珍。捕獲的對象傳遞給一個(gè)委托實(shí)現(xiàn)AVCaptureMetadataOutputObjectsDelegate協(xié)議。協(xié)議方法在指定的派發(fā)隊(duì)列(dispatch queue)上執(zhí)行。
AVCaptureVideoPreviewLayerCALayer的一個(gè)子類欣范,顯示捕獲到的相機(jī)輸出流。
好了看下實(shí)現(xiàn)過程:
添加代理 <AVCaptureMetadataOutputObjectsDelegate>
/** 設(shè)備 */
@property (nonatomic, strong) AVCaptureDevice * device;
/** 輸入輸出的中間橋梁 */
@property (nonatomic, strong) AVCaptureSession * session;
/** 相機(jī)圖層 */
@property (nonatomic, strong) AVCaptureVideoPreviewLayer * previewLayer;
/** 掃描支持的編碼格式的數(shù)組 */
@property (nonatomic, strong) NSMutableArray * metadataObjectTypes;
/** 遮罩層 */
@property (nonatomic, strong) ZFMaskView * maskView;
@property(nonatomic,strong) AVCaptureMetadataOutput * metadataOutput ;//輸出流
@property(nonatomic,strong)AVCaptureDeviceInput * input;//創(chuàng)建輸入流
這里介紹下掃描支持的編碼格式
/*
//設(shè)置支持的掃描類型
由于本項(xiàng)目只支持條形碼掃描令哟,故先屏蔽掉二維碼掃描功能
AVMetadataObjectTypeQRCode,AVMetadataObjectTypeAztecCode,
*/
- (NSMutableArray *)metadataObjectTypes{
if (!_metadataObjectTypes) {
_metadataObjectTypes = [NSMutableArray arrayWithObjects:AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, ?/ ?/我國商品碼主要就是這和 EAN8
AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeUPCECode, nil];
// >= iOS 8
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
[_metadataObjectTypes addObjectsFromArray:@[AVMetadataObjectTypeInterleaved2of5Code, AVMetadataObjectTypeITF14Code, AVMetadataObjectTypeDataMatrixCode]];
}
}
? ? return _metadataObjectTypes;
}
/**
*? 掃描初始化
*/
- (void)capture{
//獲取攝像設(shè)備
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//創(chuàng)建輸入流
AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
//創(chuàng)建輸出流
_metadataOutput = [[AVCaptureMetadataOutput alloc] init];
//設(shè)置代理 在主線程里刷新
[_metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//初始化鏈接對象
self.session = [[AVCaptureSession alloc] init];
//高質(zhì)量采集率
self.session.sessionPreset = AVCaptureSessionPresetHigh;
[self.session addInput:input];
[self.session addOutput:_metadataOutput];
self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
self.previewLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
self.previewLayer.backgroundColor = [UIColor yellowColor].CGColor;
[self.view.layer addSublayer:self.previewLayer];
//設(shè)置掃描支持的編碼格式(如下設(shè)置條形碼和二維碼兼容)
_metadataOutput.metadataObjectTypes = self.metadataObjectTypes;
//開始捕獲
[self.session startRunning];
}
下一步恼琼,獲取掃描結(jié)果
#pragma mark - AVCaptureMetadataOutputObjectsDelegate-(void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray*)metadataObjects fromConnection:(AVCaptureConnection*)connection
{if(metadataObjects.count>0) {? ? ?
? ?[self.session stopRunning];
?AVMetadataMachineReadableCodeObject*metadataObject = ?metadataObjects[0];
?NSLog(@"%@",metadataObject.stringValue);?
? }}
小結(jié)一下:
如果你的項(xiàng)目只需要掃描二維碼,不考慮條形碼屏富,metadataObjectTypes只需要AVMetadataObjectTypeQRCode就夠了晴竞,反之把這個(gè)去掉
? 下面我主要講講怎么把鏡頭拉近,提高掃描效果狠半,你之前在界面中添加一個(gè)按鈕噩死,添加事件。
#pragma mark - ?焦距
- (void)CameraScaleAction:(UIButton *)sender{
kCameraScale+=0.5; ? //去定義一個(gè)float類型神年,默認(rèn)值為1.0
if(kCameraScale>2.5)
kCameraScale=1.0;
//改變焦距 ? 記住這里的輸出鏈接類型要選中這個(gè)類型已维,否則屏幕會(huì)花的
AVCaptureConnection *connect=[_metadataOutput connectionWithMediaType:AVMediaTypeVideo];
[CATransaction begin];
[CATransaction setAnimationDuration:0.2];
[sender setTitle:[NSString stringWithFormat:@"%.1fX",(float)kCameraScale] forState:UIControlStateNormal];
//主要是改變相機(jī)圖層的大小
[_previewLayer setAffineTransform:CGAffineTransformMakeScale(kCameraScale, kCameraScale)];
connect.videoScaleAndCropFactor= kCameraScale;
[CATransaction commit];
//超出的部分切掉,否則影響掃描效果
self.view.clipsToBounds=YES;
self.view.layer.masksToBounds=YES;
}
這是對比圖,
如果想獲取焦點(diǎn)需要給view添加一個(gè)手勢
////對焦
-(void)foucus:(UITapGestureRecognizer *)sender
{
if(_input.device.position==AVCaptureDevicePositionFront)
return;
if(sender.state==UIGestureRecognizerStateRecognized)
{
CGPoint location=[sender locationInView:self.view];
//對焦
__weak typeof(self) weakSelf=self;
[self focusOnPoint:location completionHandler:^{
weakSelf.focalReticule.center=location;
weakSelf.focalReticule.alpha=0.0;
weakSelf.focalReticule.hidden=NO;
[UIView animateWithDuration:0.3 animations:^{
weakSelf.focalReticule.alpha=1.0;
}completion:^(BOOL finished) {
[UIView animateWithDuration:0.3 animations:^{
weakSelf.focalReticule.alpha=0.0;
}];
}];
}];
}
}
////對某一點(diǎn)對焦
-(void)focusOnPoint:(CGPoint)point completionHandler:(void(^)())completionHandler{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];;
CGPoint pointOfInterest = CGPointZero;
CGSize frameSize = self.view.bounds.size;
pointOfInterest = CGPointMake(point.y / frameSize.height, 1.f - (point.x / frameSize.width));
if ([device isFocusPointOfInterestSupported] && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus])
{
NSError *error;
if ([device lockForConfiguration:&error])
{
if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance])
{
[device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
}
if ([device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus])
{
[device setFocusMode:AVCaptureFocusModeAutoFocus];
[device setFocusPointOfInterest:pointOfInterest];
}
if([device isExposurePointOfInterestSupported] && [device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure])
{
[device setExposurePointOfInterest:pointOfInterest];
[device setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
}
[device unlockForConfiguration];
if(completionHandler)
completionHandler();
}
}
else{
if(completionHandler)
completionHandler();
}
} ? ? ? ? ? ? ? ??
好了瘤袖,歡迎大家指正