ZBar爲我們提供了兩種使用方式,一種是直接調用ZBar提供的ZBarReaderViewController打開一個掃描界面,另一種方式是使用ZBar提供的可以嵌在其他視圖中的ZBarReaderView,實際項目中我們更可能會使用第二種方式,這可以讓我們對界面做更多的定製。
ZBar使用起來也非常簡單,將ZBarSDK導入項目,在需要使用ZBar的文件中導入ZBarSDK.h頭文件即可,以下是ZBarReaderView的初始化方法:
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- _readerView = [[ZBarReaderView alloc] init];
- _readerView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64);
- _readerView.layer.cornerRadius = 8.0f;
- _readerView.layer.borderWidth= 1.0f;
- _readerView.layer.borderColor = [[UIColor blueColor] CGColor];
- _readerView.readerDelegate = self;
- //關閉閃光燈
- _readerView.torchMode = 0;
- //掃描區域
- CGRect scanMaskRect = CGRectMake(60, 60, 200, 200);
- if (TARGET_IPHONE_SIMULATOR) {
- ZBarCameraSimulator *cameraSimulator = [[ZBarCameraSimulator alloc] initWithViewController:self];
- cameraSimulator.readerView = _readerView;
- }
- [self.view addSubview:_readerView];
- //掃描區域計算
- _readerView.scanCrop = [self getScanCropWithScanRect:scanMaskRect andReaderViewBounds:_readerView.bounds];
- [_readerView start];
- }
以上代碼需要說明的有以下幾點:
掃描區域計算
這點比較重要,我們常用的二維碼掃描軟件的有效掃描區域一般都是中央區域,其他部分是不進行掃描的,ZBar可以通過ZBarReaderView的scanCrop屬性設置掃描區域,它的默認值是CGRect(0, 0, 1, 1),表示整個ZBarReaderView區域都是有效的掃描區域。我們需要把掃描區域座標計算爲對應的百度分數座標,也就是以上代碼中調用的getScanCrop:readerViewBounds方法,親測沒有問題,如下所示:
- - (CGRect)getScanCropWithScanRect:(CGRect)rect andReaderViewBounds:(CGRect)rvBounds
- {
- CGFloat x,y,width,height;
- x = rect.origin.y / rvBounds.size.height;
- y = 1 - (rect.origin.x + rect.size.width) / rvBounds.size.width;
- width = rect.size.height / rvBounds.size.height;
- height = rect.size.width / rvBounds.size.width;
- return CGRectMake(x, y, width, height);
- }
初始化部分完成之後,就可以調用ZBarReaderView的start方法開始掃描了,需要讓你的類實現ZBarReaderViewDelegate協議,在掃描到二維碼時會調用delegate的對應方法。最後,當二維碼已經識別時候,可以調用ZBarReaderView的stop方法停止掃描。如下所示: