實(shí)現(xiàn)iOS原生二維碼掃描

項(xiàng)目需求要是用到二維碼掃描稿黄,這次使用的是AVFoundation框架實(shí)現(xiàn)唱星。相對(duì)于ZBar和ZXing效率更高(其次這兩個(gè)庫(kù)貌似也沒(méi)有人維護(hù)了)鞭缭、而且現(xiàn)在好多app也只都支持iOS7.0及以上系統(tǒng)。


Demo地址:
github地址


效果圖

IMG_1352.PNG
IMG_1353.PNG

好了現(xiàn)在就來(lái)說(shuō)說(shuō)怎么實(shí)現(xiàn)吧

1.定義一個(gè)類QRCodeReaderView類
   #import <UIKit/UIKit.h>

  @protocol QRCodeReaderViewDelegate <NSObject>
  - (void)readerScanResult:(NSString *)result;
  @end

  @interface QRCodeReaderView : UIView

  @property (nonatomic, weak)id<QRCodeReaderViewDelegate> delegate;
  @property (nonatomic,copy)UIImageView * readLineView;
  @property (nonatomic,assign)BOOL is_Anmotion;
  @property (nonatomic,assign)BOOL is_AnmotionFinished;

  //開(kāi)啟關(guān)閉掃描
  - (void)start;
  - (void)stop;

  - (void)loopDrawLine;//初始化掃描線

  @end
2.看看.m的實(shí)現(xiàn)
 #import "QRCodeReaderView.h"
 #import <AVFoundation/AVFoundation.h>

 #define DeviceMaxHeight ([UIScreen      mainScreen].bounds.size.height)
 #define DeviceMaxWidth ([UIScreen      mainScreen].bounds.size.width)
 #define widthRate DeviceMaxWidth/320

 #define contentTitleColorStr @"666666" //正文顏色較深
 
 @interface QRCodeReaderView ()  <AVCaptureMetadataOutputObjectsDelegate>
 {
     //采集流
     AVCaptureSession * session;
     NSTimer * countTime;
 }
 @property (nonatomic, strong) CAShapeLayer *overlay;
 @end

 @implementation QRCodeReaderView

 - (id)initWithFrame:(CGRect)frame
 {
     if ((self = [super initWithFrame:frame])) {
         //初始化
         [self instanceDevice];
   }

   return self;
 }     
初始化并創(chuàng)建
 - (void)instanceDevice
 {
     //掃描區(qū)域
     UIImage *hbImage=[UIImage imageNamed:@"scanscanBg"];
     UIImageView * scanZomeBack=[[UIImageView alloc] init];
     scanZomeBack.backgroundColor = [UIColor clearColor];
     scanZomeBack.layer.borderColor = [UIColor whiteColor].CGColor;
     scanZomeBack.layer.borderWidth = 2.5;
     scanZomeBack.image = hbImage;
     //添加一個(gè)背景圖片
     CGRect mImagerect = CGRectMake(60*widthRate, (DeviceMaxHeight-200*widthRate)/2, 200*widthRate,      200*widthRate);
     [scanZomeBack setFrame:mImagerect];
     CGRect scanCrop=[self getScanCrop:mImagerect readerViewBounds:self.frame];
     [self addSubview:scanZomeBack];

     //獲取攝像設(shè)備
     AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
     //創(chuàng)建輸入流
     AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
     //創(chuàng)建輸出流
     AVCaptureMetadataOutput * output =      [[AVCaptureMetadataOutput alloc]init];
     //設(shè)置代理 在主線程里刷新
     [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
output.rectOfInterest = scanCrop;

     //初始化鏈接對(duì)象
     session = [[AVCaptureSession alloc]init];
     //高質(zhì)量采集率
     [session setSessionPreset:AVCaptureSessionPresetHigh];
     if (input) {
         [session addInput:input];
     }
     if (output) {
         [session addOutput:output];
         //設(shè)置掃碼支持的編碼格式(如下設(shè)置條形碼和二維碼兼容)
         NSMutableArray *a = [[NSMutableArray alloc] init];
         if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode]) {
             [a addObject:AVMetadataObjectTypeQRCode];
         }
         if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeEAN13Code]) {
             [a addObject:AVMetadataObjectTypeEAN13Code];
         }
         if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeEAN8Code]) {
             [a addObject:AVMetadataObjectTypeEAN8Code];
         }
         if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeCode128Code]) {
             [a addObject:AVMetadataObjectTypeCode128Code];
         }
         output.metadataObjectTypes=a;
     }

     AVCaptureVideoPreviewLayer * layer =      [AVCaptureVideoPreviewLayer layerWithSession:session];
     layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
     layer.frame=self.layer.bounds;
     [self.layer insertSublayer:layer atIndex:0];

     [self setOverlayPickerView:self];

     //開(kāi)始捕獲
     [session startRunning];

     }
掃描線條
 -(void)loopDrawLine
 {
     _is_AnmotionFinished = NO;
     CGRect rect = CGRectMake(60*widthRate,      (DeviceMaxHeight-200*widthRate)/2, 200*widthRate, 2);
     if (_readLineView) {
         _readLineView.alpha = 1;
         _readLineView.frame = rect;
     }
     else{
         _readLineView = [[UIImageView alloc] initWithFrame:rect];
         [_readLineView setImage:[UIImage imageNamed:@"scanLine"]];
         [self addSubview:_readLineView];
     }

     [UIView animateWithDuration:1.5 animations:^{
         //修改fream的代碼寫在這里
         _readLineView.frame =CGRectMake(60*widthRate, (DeviceMaxHeight-200*widthRate)/2+200*widthRate-5, 200*widthRate, 2);
} completion:^(BOOL finished) {
         if (!_is_Anmotion) {
             [self loopDrawLine];
         }
         _is_AnmotionFinished = YES;
     }];
 }

 - (void)setOverlayPickerView:(QRCodeReaderView *)reader
 {

     CGFloat wid = 60*widthRate;
     CGFloat heih = (DeviceMaxHeight-200*widthRate)/2;

     //最上部view
     CGFloat alpha = 0.6;
     UIView* upView = [[UIView alloc]      initWithFrame:CGRectMake(0, 0, DeviceMaxWidth, heih)];
     upView.alpha = alpha;
     upView.backgroundColor = [self colorFromHexRGB:contentTitleColorStr];
     [reader addSubview:upView];

     //用于說(shuō)明的label
     UILabel * labIntroudction= [[UILabel alloc] init];
     labIntroudction.backgroundColor = [UIColor clearColor];
     labIntroudction.frame=CGRectMake(0, 64+(heih-64-50*widthRate)/2, DeviceMaxWidth, 50*widthRate);
     labIntroudction.textAlignment = NSTextAlignmentCenter;
     labIntroudction.textColor=[UIColor whiteColor];
     labIntroudction.text=@"將二維碼放入框中魏颓,即自動(dòng)掃描";
     [upView addSubview:labIntroudction];

     //左側(cè)的view
     UIView * cLeftView = [[UIView alloc] initWithFrame:CGRectMake(0, heih, wid, 200*widthRate)];
     cLeftView.alpha = alpha;
     cLeftView.backgroundColor = [self colorFromHexRGB:contentTitleColorStr];
     [reader addSubview:cLeftView];

     //右側(cè)的view
     UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(DeviceMaxWidth-wid, heih, wid, 200*widthRate)];
     rightView.alpha = alpha;
     rightView.backgroundColor = [self colorFromHexRGB:contentTitleColorStr];
     [reader addSubview:rightView];

     //底部view
     UIView * downView = [[UIView alloc] initWithFrame:CGRectMake(0, heih+200*widthRate, DeviceMaxWidth, DeviceMaxHeight - heih-200*widthRate)];
     downView.alpha = alpha;
     downView.backgroundColor = [self      colorFromHexRGB:contentTitleColorStr];
     [reader addSubview:downView];

 - (void)turnBtnEvent:(UIButton *)button_
 {
     button_.selected = !button_.selected;
     if (button_.selected) {
         [self turnTorchOn:YES];
     }
     else{
         [self turnTorchOn:NO];
     }

 }

掃描區(qū)域

-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:         (CGRect)readerViewBounds
 {

         CGFloat x,y,width,height;
         x = (CGRectGetHeight(readerViewBounds)-CGRectGetHeight(rect))/2/CGRectGetHeight(readerViewBounds);
         y = (CGRectGetWidth(readerViewBounds)-CGRectGetWidth(rect))/2/CGRectGetWidth(readerViewBounds);
         width = CGRectGetHeight(rect)/CGRectGetHeight(readerViewBounds);
         height = CGRectGetWidth(rect)/CGRectGetWidth(readerViewBounds);

         return CGRectMake(x, y, width, height);

}

開(kāi)始掃描

- (void)start
  {
    [session startRunning];
  }

停止掃描

- (void)stop
{
   [session stopRunning];
}

掃描結(jié)果

 - (void)captureOutput:(AVCaptureOutput *)captureOutput      didOutputMetadataObjects:(NSArray *)metadataObjects        fromConnection:(AVCaptureConnection *)connection
{
  if (metadataObjects && metadataObjects.count>0) {
     AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
     //輸出掃描字符串
     if (_delegate && [_delegate respondsToSelector:@selector(readerScanResult:)]) {
        [_delegate readerScanResult:metadataObject.stringValue];
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末岭辣,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子甸饱,更是在濱河造成了極大的恐慌沦童,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,539評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件叹话,死亡現(xiàn)場(chǎng)離奇詭異偷遗,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)驼壶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門氏豌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人热凹,你說(shuō)我怎么就攤上這事泵喘。” “怎么了般妙?”我有些...
    開(kāi)封第一講書人閱讀 165,871評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵纪铺,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我碟渺,道長(zhǎng)鲜锚,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,963評(píng)論 1 295
  • 正文 為了忘掉前任苫拍,我火速辦了婚禮芜繁,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘绒极。我一直安慰自己骏令,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,984評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布集峦。 她就那樣靜靜地躺著伏社,像睡著了一般。 火紅的嫁衣襯著肌膚如雪塔淤。 梳的紋絲不亂的頭發(fā)上摘昌,一...
    開(kāi)封第一講書人閱讀 51,763評(píng)論 1 307
  • 那天,我揣著相機(jī)與錄音高蜂,去河邊找鬼聪黎。 笑死,一個(gè)胖子當(dāng)著我的面吹牛备恤,可吹牛的內(nèi)容都是我干的稿饰。 我是一名探鬼主播,決...
    沈念sama閱讀 40,468評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼露泊,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼喉镰!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起惭笑,我...
    開(kāi)封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤侣姆,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后沉噩,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體捺宗,經(jīng)...
    沈念sama閱讀 45,850評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,002評(píng)論 3 338
  • 正文 我和宋清朗相戀三年川蒙,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蚜厉。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,144評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡畜眨,死狀恐怖昼牛,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情康聂,我是刑警寧澤匾嘱,帶...
    沈念sama閱讀 35,823評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站早抠,受9級(jí)特大地震影響霎烙,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜蕊连,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,483評(píng)論 3 331
  • 文/蒙蒙 一悬垃、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧甘苍,春花似錦尝蠕、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,026評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)廊佩。三九已至,卻和暖如春靖榕,著一層夾襖步出監(jiān)牢的瞬間标锄,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,150評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工茁计, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留料皇,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,415評(píng)論 3 373
  • 正文 我出身青樓星压,卻偏偏與公主長(zhǎng)得像践剂,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子娜膘,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,092評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容