iOS開發-QRCode-二維碼識別與生成

jopen 8年前發布 | 79K 次閱讀 iOS開發 移動開發

有關二維碼的介紹,我這里不做過多說明, 可以直接去基維百科查看,附上鏈接 QR code .

IOS7之前,開發者進行掃碼編程時,一般會借助第三方庫。常用的是 ZBarSDKaZXingObjC ,IOS7之后,系統的AVMetadataObject類中,為我們提供了解析二維碼的接口。經過測試,使用原生API掃描和處理的效率非常高,遠遠高于第三方庫。

掃描

官方提供的接口非常簡單,直接看代碼,主要使用的是AVFoundation。

@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>//用于處理采集信息的代理
{
    AVCaptureSession * session;//輸入輸出的中間橋梁
}
@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //獲取攝像設備
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //創建輸入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    if (!input) return;
    //創建輸出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    //設置代理 在主線程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //設置有效掃描區域
    CGRect scanCrop=[self getScanCrop:_scanWindow.bounds readerViewBounds:self.view.frame];
     output.rectOfInterest = scanCrop;
    //初始化鏈接對象
    _session = [[AVCaptureSession alloc]init];
    //高質量采集率
    [_session setSessionPreset:AVCaptureSessionPresetHigh];

    [_session addInput:input];
    [_session addOutput:output];
    //設置掃碼支持的編碼格式(如下設置條形碼和二維碼兼容)
    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];
    //開始捕獲
    [_session startRunning];
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        //[session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        //輸出掃描字符串
        NSLog(@"%@",metadataObject.stringValue);
    }
}

一些初始化的代碼加上實現代理方法便完成了二維碼掃描的工作,這里我們需要注意的是, 在二維碼掃描的時候, 我們一般都會在屏幕中間放一個方框,用來顯示二維碼掃描的大小區間,這里我們在個 AVCaptureMetadataOutput 類中有一個 rectOfInterest 屬性,它的作用就是設置掃描范圍。

這個CGRect參數和普通的Rect范圍不太一樣,它的四個值的范圍都是0-1,表示比例。

rectOfInterest都是按照橫屏來計算的 所以當豎屏的情況下 x軸和y軸要交換一下。

寬度和高度設置的情況也是類似。

我們在上面設置有效掃描區域的方法如下

#pragma mark-> 獲取掃描區域的比例關系
-(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);

}

讀取

讀取主要用到CoreImage 不過要強調的是讀取二維碼的功能只有在iOS8之后才支持,我們需要在相冊中調用一個二維碼,將其讀取,代碼如下

#pragma mark-> 我的相冊
-(void)myAlbum{

    NSLog(@"我的相冊");
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        //1.初始化相冊拾取器
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        //2.設置代理
        controller.delegate = self;
        //3.設置資源:
        /**
         UIImagePickerControllerSourceTypePhotoLibrary,相冊
         UIImagePickerControllerSourceTypeCamera,相機
         UIImagePickerControllerSourceTypeSavedPhotosAlbum,照片庫
         */
        controller.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        //4.隨便給他一個轉場動畫
        controller.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        [self presentViewController:controller animated:YES completion:NULL];

    }else{

        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"設備不支持訪問相冊,請在設置->隱私->照片中進行設置!" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
        [alert show];
    }

}

完成相冊代理, 我們在代理中添加讀取二維碼方法

#pragma mark-> imagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //1.獲取選擇的圖片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    //2.初始化一個監測器
    CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];

    [picker dismissViewControllerAnimated:YES completion:^{
        //監測到的結果數組
        NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
        if (features.count >=1) {
            /**結果對象 */
            CIQRCodeFeature *feature = [features objectAtIndex:0];
            NSString *scannedResult = feature.messageString;
            UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"掃描結果" message:scannedResult delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
            [alertView show];

        }
        else{
            UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"該圖片沒有包含一個二維碼!" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
            [alertView show];

        }


    }];


}

因為沒用真機,所以這里沒有給出太多的截圖, 用模擬器讀取自帶圖片,結果如下

生成

生成二維碼,其實也是用到CoreImage,但是步驟繁瑣一些,代碼如下

#pragma mark-> 二維碼生成
-(void)create{

    UIImage *image=[UIImage imageNamed:@"6824500_006_thumb.jpg"];
    NSString*tempStr;
    if(self.textField.text.length==0){

        tempStr=@"ddddddddd";

    }else{

        tempStr=self.textField.text;

    }
    UIImage*tempImage=[QRCodeGenerator qrImageForString:tempStr imageSize:360 Topimg:image withColor:RandomColor];

    _outImageView.image=tempImage;

}
+(UIImage*)qrImageForString:(NSString *)string imageSize:(CGFloat)size Topimg:(UIImage *)topimg withColor:(UIColor*)color{

    if (![string length]) {
        return nil;
    }

    QRcode *code = QRcode_encodeString([string UTF8String], 0, QR_ECLEVEL_L, QR_MODE_8, 1);
    if (!code) {
        return nil;
    }

    // create context
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(0, size, size, 8, size * 4, colorSpace, kCGImageAlphaPremultipliedLast);

    CGAffineTransform translateTransform = CGAffineTransformMakeTranslation(0, -size);
    CGAffineTransform scaleTransform = CGAffineTransformMakeScale(1, -1);
    CGContextConcatCTM(ctx, CGAffineTransformConcat(translateTransform, scaleTransform));

    // draw QR on this context
    [QRCodeGenerator drawQRCode:code context:ctx size:size withPointType:0 withPositionType:0 withColor:color];

    // get image
    CGImageRef qrCGImage = CGBitmapContextCreateImage(ctx);
    UIImage * qrImage = [UIImage imageWithCGImage:qrCGImage];

    if(topimg)
    {
        UIGraphicsBeginImageContext(qrImage.size);

        //Draw image2
        [qrImage drawInRect:CGRectMake(0, 0, qrImage.size.width, qrImage.size.height)];

        //Draw image1
        float r=qrImage.size.width*35/240;
        [topimg drawInRect:CGRectMake((qrImage.size.width-r)/2, (qrImage.size.height-r)/2 ,r, r)];

        qrImage=UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();
    }

    // some releases
    CGContextRelease(ctx);
    CGImageRelease(qrCGImage);
    CGColorSpaceRelease(colorSpace);
    QRcode_free(code);

    return qrImage;

}
+ (void)drawQRCode:(QRcode *)code context:(CGContextRef)ctx size:(CGFloat)size withPointType:(QRPointType)pointType withPositionType:(QRPositionType)positionType withColor:(UIColor *)color {
    unsigned char *data = 0;
    int width;
    data = code->data;
    width = code->width;
    float zoom = (double)size / (code->width + 2.0 * qr_margin);
    CGRect rectDraw = CGRectMake(0, 0, zoom, zoom);

    // draw
    const CGFloat *components;
    if (color) {
        components = CGColorGetComponents(color.CGColor);
    }else {
        components = CGColorGetComponents([UIColor blackColor].CGColor);
    }
    CGContextSetRGBFillColor(ctx, components[0], components[1], components[2], 1.0);
    NSLog(@"aad :%f  bbd :%f   ccd:%f",components[0],components[1],components[2]);

    for(int i = 0; i < width; ++i) {
        for(int j = 0; j < width; ++j) {
            if(*data & 1) {
                rectDraw.origin = CGPointMake((j + qr_margin) * zoom,(i + qr_margin) * zoom);
                if (positionType == QRPositionNormal) {
                    switch (pointType) {
                        case QRPointRect:
                            CGContextAddRect(ctx, rectDraw);
                            break;
                        case QRPointRound:
                            CGContextAddEllipseInRect(ctx, rectDraw);
                            break;
                        default:
                            break;
                    }
                }else if(positionType == QRPositionRound) {
                    switch (pointType) {
                        case QRPointRect:
                            CGContextAddRect(ctx, rectDraw);
                            break;
                        case QRPointRound:
                            if ((i>=0 && i<=6 && j>=0 && j<=6) || (i>=0 && i<=6 && j>=width-7-1 && j<=width-1) || (i>=width-7-1 && i<=width-1 && j>=0 && j<=6)) {
                                CGContextAddRect(ctx, rectDraw);
                            }else {
                                CGContextAddEllipseInRect(ctx, rectDraw);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            ++data;
        }
    }
    CGContextFillPath(ctx);
}

在textField輸入,生成下圖

長按二維碼識別

這個功能有很多的地方在用, 最讓人熟知的我想便是微信了,其實實現方法還是很簡單的。

 #pragma mark-> 長按識別二維碼
-(void)dealLongPress:(UIGestureRecognizer*)gesture{

    if(gesture.state==UIGestureRecognizerStateBegan){

        _timer.fireDate=[NSDate distantFuture];

        UIImageView*tempImageView=(UIImageView*)gesture.view;
        if(tempImageView.image){
            //1. 初始化掃描儀,設置設別類型和識別質量
            CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
            //2. 掃描獲取的特征組
            NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:tempImageView.image.CGImage]];
            //3. 獲取掃描結果
            CIQRCodeFeature *feature = [features objectAtIndex:0];
            NSString *scannedResult = feature.messageString;
            UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"掃描結果" message:scannedResult delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
            [alertView show];
        }else {

            UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"掃描結果" message:@"您還沒有生成二維碼" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
            [alertView show];
        }


    }else if (gesture.state==UIGestureRecognizerStateEnded){


        _timer.fireDate=[NSDate distantPast];
    }


}

我們用剛才生成的二維碼進行長按識別,效果如下

結語

本文demo下載地址請點這里 Demo ,

轉自 mokey1422 所寫的仿支付寶二維碼。

系統原生的二維碼掃描掃描識別速度,要比第三方好用得多,在沒有特殊原因的情況下,比如7.0系統以下,我希望大家都能用系統原生的方法。

文章若有問題請給予指正,感謝。

來自: http://yimouleng.com/2016/01/13/ios-QRCode/

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!