二維碼生成/掃描

調(diào)用攝像頭和相冊,需要在plist文件里增加鍵值對:
Privacy - Camera Usage Description 如果不允許,您將無法使用攝像頭
Privacy - Photo Library Usage Description 如果不允許倍宾,您將無法使用相冊

- (void)createView {
    //生成按鈕
    UIButton *createBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScaleX*40, kScaleY*450, kScaleX*100, kScaleY*60)];
    [createBtn setTitle:@"生成" forState:UIControlStateNormal];
    [createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    createBtn.titleLabel.font = [UIFont fontWithName:LightFont size:18];
    createBtn.backgroundColor = [UIColor blackColor];
    createBtn.layer.cornerRadius = 4;
    createBtn.clipsToBounds = YES;
    [createBtn addTarget:self action:@selector(createAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:createBtn];
    
    //掃描按鈕
    UIButton *scannerBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScaleX*235, kScaleY*450, kScaleX*100, kScaleY*60)];
    [scannerBtn setTitle:@"掃描" forState:UIControlStateNormal];
    [scannerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    scannerBtn.titleLabel.font = [UIFont fontWithName:LightFont size:18];
    scannerBtn.backgroundColor = [UIColor blackColor];
    scannerBtn.layer.cornerRadius = 4;
    scannerBtn.clipsToBounds = YES;
    [scannerBtn addTarget:self action:@selector(scannerAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scannerBtn];
}

生成:

- (void)createAction {
    //1.創(chuàng)建濾鏡
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    //2.恢復(fù)默認(rèn)
    [filter setDefaults];
    
    //3.給濾鏡添加數(shù)據(jù)
    NSString *dataString = @"你好,世界";
    //將數(shù)據(jù)轉(zhuǎn)換成NSData類型
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    //通過KVC設(shè)置濾鏡的二維碼輸入信息
    [filter setValue:data forKey:@"inputMessage"];
    
    //4.獲取輸出的二維碼圖片(CIImage類型)
    CIImage *outImage = [filter outputImage];
    //將CIImage類型的圖片裝換成UIImage類型的圖片
    UIImage *image = [self excludeFuzzyImageFromCIImage:outImage size:kScaleY*200];
    
    //5.顯示二維碼圖片
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(kScaleX*87.5, 64+kScaleY*40, kScaleX*200, kScaleY*200)];
    imageV.image = image;
    [self.view addSubview:imageV];
}
#pragma mark -- 對圖像進(jìn)行清晰處理,很關(guān)鍵胜嗓!
- (UIImage *)excludeFuzzyImageFromCIImage:(CIImage *)image size:(CGFloat)size {
    
    CGRect extent = CGRectIntegral(image.extent);
    
    //通過比例計算高职,讓最終的圖像大小合理(正方形是我們想要的)
    CGFloat scale = MIN(size / CGRectGetWidth(extent), size / CGRectGetHeight(extent));
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpace, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext * context = [CIContext contextWithOptions: nil];
    
    CGImageRef bitmapImage = [context createCGImage: image fromRect: extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    //切記ARC模式下是不會對CoreFoundation框架的對象進(jìn)行自動釋放的,所以要我們手動釋放
    CGContextRelease(bitmapRef);
    
    CGImageRelease(bitmapImage);
    
    CGColorSpaceRelease(colorSpace);
    
    return [UIImage imageWithCGImage: scaledImage];
}

掃描:

import <AVFoundation/AVFoundation.h>

遵守<AVCaptureMetadataOutputObjectsDelegate>協(xié)議辞州,用于處理采集信息
使用到的全局變量:

@implementation ScannerViewController
{
    AVCaptureSession *session;//輸入輸出的中間橋梁
    NSTimer *timer;
    UIImageView *line;
}
- (void)scannerAction {
    //先判斷攝像頭硬件是否好用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //用戶是否允許攝像頭使用
        NSString *mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        //不允許彈出提示框
        if (authorizationStatus == AVAuthorizationStatusRestricted || authorizationStatus == AVAuthorizationStatusDenied) {
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"攝像頭訪問受限" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertView animated:YES completion:nil];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
            [alertView addAction:action];
        }else {
            //這里是攝像頭可以使用的處理邏輯
            [self addCamera];
        }
    }else {
        // 硬件問題提示
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"手機(jī)攝像頭設(shè)備損壞" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertView animated:YES completion:nil];
    }
}
- (void)addCamera {
    //獲取攝像設(shè)備
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //創(chuàng)建輸入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //創(chuàng)建輸出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc]init];
    //設(shè)置掃描區(qū)域
    CGSize size = self.view.bounds.size;
    CGRect cropRect = CGRectMake(UI_SCREEN_WIDTH/375*37.5, 64+UI_SCREEN_HEIGHT/667*70, UI_SCREEN_WIDTH/375*300, UI_SCREEN_HEIGHT/667*300);
    CGFloat p1 = size.height/size.width;
    CGFloat p2 = 1920./1080.;  //使用了1080p的圖像輸出
    if (p1 < p2) {
        CGFloat fixHeight = self.view.bounds.size.width * 1920. / 1080.;
        CGFloat fixPadding = (fixHeight - size.height)/2;
        output.rectOfInterest = CGRectMake((cropRect.origin.y + fixPadding)/fixHeight,
                                           cropRect.origin.x/size.width,
                                           cropRect.size.height/fixHeight,
                                           cropRect.size.width/size.width);
    }else {
        CGFloat fixWidth = self.view.bounds.size.height * 1080. / 1920.;
        CGFloat fixPadding = (fixWidth - size.width)/2;
        output.rectOfInterest = CGRectMake(cropRect.origin.y/size.height,
                                           (cropRect.origin.x + fixPadding)/fixWidth,
                                           cropRect.size.height/size.height,
                                           cropRect.size.width/fixWidth);
    }
    //設(shè)置代理 在主線程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //初始化鏈接對象
    session = [[AVCaptureSession alloc]init];
    //高質(zhì)量采集率
    [session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [session addInput:input];
    [session addOutput:output];
    //設(shè)置掃碼支持的編碼格式(如下設(shè)置條形碼和二維碼兼容)
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    
    [self creatScannerUI];
    
    [self lineMove];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(lineMove) name:@"move" object:nil];
    
    //開始捕獲
    [session startRunning];
}

掃描UI:

- (void)creatScannerUI {
    //掃碼窗口
    UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64)];
    
    maskView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    
    [self.view addSubview:maskView];
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    
    [maskPath appendPath:[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(UI_SCREEN_WIDTH/375*67.5, UI_SCREEN_HEIGHT/667*100, UI_SCREEN_WIDTH/375*240, UI_SCREEN_HEIGHT/667*240) cornerRadius:1] bezierPathByReversingPath]];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    
    maskLayer.path = maskPath.CGPath;
    
    maskView.layer.mask = maskLayer;
    
    //掃描動畫
    line = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH/375*67.5, 64+UI_SCREEN_HEIGHT/667*100, UI_SCREEN_WIDTH/375*240, 2)];
    line.image = [UIImage imageNamed:@"掃描線"];
    line.center = CGPointMake(UI_SCREEN_WIDTH/2, 64+UI_SCREEN_HEIGHT/667*100);
    [self.view addSubview:line];
    
    UIImageView *borderImg = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH/375*67.5, 64+UI_SCREEN_HEIGHT/667*100, UI_SCREEN_WIDTH/375*240, UI_SCREEN_HEIGHT/667*240)];
    borderImg.image = [UIImage imageNamed:@"掃描框"];
    [self.view addSubview:borderImg];
}

//動畫
- (void)lineMove {
    [UIView animateWithDuration:2.5 delay:0.0 options:UIViewAnimationOptionRepeat animations:^{
        line.center = CGPointMake(UI_SCREEN_WIDTH/2, 64+UI_SCREEN_HEIGHT/667*338);
    } completion:nil];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"move" object:nil];
}
//掃碼代理
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects.count>0) {
        //[session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex :0];
        //輸出掃描字符串
        NSLog(@"%@",metadataObject.stringValue);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末怔锌,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子变过,更是在濱河造成了極大的恐慌埃元,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,843評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件媚狰,死亡現(xiàn)場離奇詭異岛杀,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)崭孤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評論 3 392
  • 文/潘曉璐 我一進(jìn)店門类嗤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人辨宠,你說我怎么就攤上這事遗锣。” “怎么了嗤形?”我有些...
    開封第一講書人閱讀 163,187評論 0 353
  • 文/不壞的土叔 我叫張陵精偿,是天一觀的道長。 經(jīng)常有香客問我,道長笔咽,這世上最難降的妖魔是什么墓阀? 我笑而不...
    開封第一講書人閱讀 58,264評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮拓轻,結(jié)果婚禮上斯撮,老公的妹妹穿的比我還像新娘。我一直安慰自己扶叉,他們只是感情好勿锅,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,289評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著枣氧,像睡著了一般溢十。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上达吞,一...
    開封第一講書人閱讀 51,231評論 1 299
  • 那天张弛,我揣著相機(jī)與錄音,去河邊找鬼酪劫。 笑死吞鸭,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的覆糟。 我是一名探鬼主播刻剥,決...
    沈念sama閱讀 40,116評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼滩字!你這毒婦竟也來了造虏?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,945評論 0 275
  • 序言:老撾萬榮一對情侶失蹤麦箍,失蹤者是張志新(化名)和其女友劉穎漓藕,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體挟裂,經(jīng)...
    沈念sama閱讀 45,367評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡享钞,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,581評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了话瞧。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嫩与。...
    茶點(diǎn)故事閱讀 39,754評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖交排,靈堂內(nèi)的尸體忽然破棺而出划滋,到底是詐尸還是另有隱情,我是刑警寧澤埃篓,帶...
    沈念sama閱讀 35,458評論 5 344
  • 正文 年R本政府宣布处坪,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏同窘。R本人自食惡果不足惜玄帕,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,068評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望想邦。 院中可真熱鬧裤纹,春花似錦、人聲如沸丧没。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽呕童。三九已至漆际,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間夺饲,已是汗流浹背奸汇。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留往声,地道東北人擂找。 一個月前我還...
    沈念sama閱讀 47,797評論 2 369
  • 正文 我出身青樓,卻偏偏與公主長得像烁挟,于是被迫代替她去往敵國和親婴洼。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,654評論 2 354

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