掃描功能小結 (掃描二維碼、條形碼)

来源:http://www.cnblogs.com/linzhengbo/archive/2017/05/09/6831159.html
-Advertisement-
Play Games

此次掃碼功能以iOS系統原生的AVFoundation框架為基礎。 廢話不多說,直接上代碼 #import <UIKit/UIKit.h> @interface ScanViewController : UIViewController @end 在.m文件中創建對象 #import "ScanVi ...


此次掃碼功能以iOS系統原生的AVFoundation框架為基礎。

廢話不多說,直接上代碼

#import <UIKit/UIKit.h>

@interface ScanViewController : UIViewController

@end
創建掃描界面

在.m文件中創建對象

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>

#import "UserInputCodeViewController.h"
#import "ScanResultViewController.h"

@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong) AVCaptureDevice *device;

@property (nonatomic, strong) AVCaptureDeviceInput *input;

@property (nonatomic, strong) AVCaptureMetadataOutput *output;

@property (nonatomic, strong) AVCaptureSession *session;

@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

/*** 專門用於保存描邊的圖層 ***/
@property (nonatomic,strong) CALayer *containerLayer;
/**
 掃描範圍
 */
@property(nonatomic, strong) UIView *scanFrame;
@property(nonatomic, strong) UIView *line;

//@property (nonatomic, strong) UIImageView *scanArea;
@property (nonatomic, strong) UILabel *lightLb;

/**
 是否打開燈光
 */
@property (nonatomic, assign) BOOL isLightOn;

@end

@implementation ScanViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!_session ) {
        [self startScan];
    }
    [self refreshScanLineAnimation];
}

-(void)refreshScanLineAnimation {
    if (_line) {
        [self scanLineAnimate];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"掃碼開鎖";
    self.view.backgroundColor = [UIColor whiteColor];
    
    _isLightOn = NO;
    
    [self initViews];
    
    [self initConner];
    
    [self startScan];
}

-(void)initViews {
    CGRect frame = CGRectZero;
    
    frame.origin.x = (SCREEN_WIDTH - 230) / 2;
    frame.origin.y = (SCREEN_HEIGHT - 500) / 2;
    frame.size.width = 230;
    frame.size.height= 230;
    
    UIView* view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor= [UIColor clearColor];
    view.layer.borderWidth = 1;
    view.layer.borderColor = [[UIColor grayColor] CGColor];
    self.scanFrame = view;
    [self.view addSubview:view];
    
    //top
    UIView* shadow = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, view.frame.origin.y)];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    //bottom
    shadow = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.origin.y + view.frame.size.height, SCREEN_WIDTH, SCREEN_HEIGHT - (view.frame.origin.y + view.frame.size.height))];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    //left
    shadow = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.origin.y, (SCREEN_WIDTH - view.frame.size.width) / 2, view.frame.size.height)];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    //right
    shadow = [[UIView alloc] initWithFrame:CGRectMake(view.frame.origin.x + view.frame.size.width, view.frame.origin.y, (SCREEN_WIDTH - view.frame.size.width) / 2, view.frame.size.height)];
    shadow.backgroundColor = [UIColor blackColor];
    shadow.alpha = 0.5;
    [self.view addSubview:shadow];
    
    _line = [[UIView alloc] initWithFrame:CGRectMake(view.frame.origin.x + 1, view.frame.origin.y + 1, frame.size.width - 2, 3)];
    _line.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:_line];
    
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(view.frame) + HEIGTHCUSTOME(70), _line.frame.size.width, 15)];
    label.font = UIFontWithPX(26);
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.center = CGPointMake(_line.center.x, label.center.y);
    label.text = @"請對準充電箱上的二維碼";
    [self.view addSubview:label];
    
    //light
    UIButton* light = [UIButton buttonWithType:UIButtonTypeCustom];
    light.frame = CGRectMake(0, view.frame.origin.y + view.frame.size.height + 120, 100, 100);
//    light.center = CGPointMake(view.frame.origin.x + view.frame.size.width - 50, light.center.y);
    light.center = CGPointMake(view.center.x, light.center.y);
    light.backgroundColor = [UIColor clearColor];
    [light setImage:IMAGE(@"flashlight_off") forState:UIControlStateNormal];
    [light addTarget:self action:@selector(openLight:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:light];
    
    _lightLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
    _lightLb.center = CGPointMake(light.center.x, light.center.y + 50);
    _lightLb.text = @"打開手電筒筒";
    _lightLb.textAlignment = NSTextAlignmentCenter;
    _lightLb.textColor = [UIColor whiteColor];
    _lightLb.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:_lightLb];
}

- (void)initConner {
    CGFloat w = 2;
    CGFloat h = 10;
    CGFloat d = 2;
    CGPoint point = CGPointZero;
    
    //left - top
    point = CGPointMake(_scanFrame.frame.origin.x - w - d, _scanFrame.frame.origin.y - w - d);
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    //left - down
    point = CGPointMake(_scanFrame.frame.origin.x - w - d, _scanFrame.frame.origin.y + _scanFrame.frame.size.height + d + w - h);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    point = CGPointMake(point.x, _scanFrame.frame.origin.y + _scanFrame.frame.size.height + d);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    //right - top
    point = CGPointMake(_scanFrame.frame.origin.x + _scanFrame.frame.size.width + d, _scanFrame.frame.origin.y - w - d);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    point = CGPointMake(_scanFrame.frame.origin.x + _scanFrame.frame.size.width + w + d - h, point.y);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    //right - down
    point = CGPointMake(_scanFrame.frame.origin.x + _scanFrame.frame.size.width + d, _scanFrame.frame.origin.y + _scanFrame.frame.size.height + w + d - h);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, w, h)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
    
    point = CGPointMake(point.x + w - h, _scanFrame.frame.origin.y + _scanFrame.frame.size.height + d);
    view = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, h, w)];
    view.backgroundColor = UIColorFromRGB(0x28a0f0);
    [self.view addSubview:view];
}

- (void)scanLineAnimate {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:2];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationRepeatAutoreverses:YES];
    [UIView setAnimationRepeatCount:HUGE_VALF];
    _line.center = CGPointMake(_line.center.x, _scanFrame.frame.origin.y + _scanFrame.frame.size.height - 5);
    [UIView commitAnimations];
}

- (void)openLight:(UIButton*)sender {
    [_device lockForConfiguration:nil];
    if (!sender.selected) {
        [sender setImage:IMAGE(@"flashlight_on") forState:UIControlStateNormal];
        [_device setTorchMode:AVCaptureTorchModeOn];
        [_device setFlashMode:AVCaptureFlashModeOn];
        _lightLb.text = @"關閉手電筒筒";
        sender.selected = YES;
    } else {
        [sender setImage:IMAGE(@"flashlight_off") forState:UIControlStateNormal];
        [_device setTorchMode:AVCaptureTorchModeOff];
        [_device setFlashMode:AVCaptureFlashModeOff];
        _lightLb.text = @"打開手電筒筒";
        sender.selected = NO;
    }
    [_device unlockForConfiguration];
}

- (void)startScan {
    if (![self.session canAddInput:self.input]) return;
    [self.session addInput:self.input];
    
    if (![self.session canAddOutput:self.output]) return;
    [self.session addOutput:self.output];
    
//    self.output.metadataObjectTypes = self.output.availableMetadataObjectTypes;     // 如此設置,可掃描二維碼、條形碼
    [self.output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    
    [self.view.layer addSublayer:self.containerLayer];
   
    [self.session startRunning];
}

- (void)drawLine:(AVMetadataMachineReadableCodeObject *)objc {
    NSArray *array = objc.corners;
    
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.lineWidth = 2;
    layer.strokeColor = [UIColor greenColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    
    UIBezierPath *path = [[UIBezierPath alloc] init];
    CGPoint point = CGPointZero;
    int index = 0;
    
    CFDictionaryRef dict = (__bridge CFDictionaryRef)(array[index++]);
    CGPointMakeWithDictionaryRepresentation(dict, &point);
    
    [path moveToPoint:point];
    
    for (int i = 1; i<array.count; i++) {
        CGPointMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)array[i], &point);
        [path addLineToPoint:point];
    }
    [path closePath];
    layer.path = path.CGPath;
    [self.containerLayer addSublayer:layer];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (_session) {
        [_session stopRunning];
    }
    [_output setMetadataObjectsDelegate:nil queue:dispatch_get_main_queue()];
    
    // id 類型不能點語法,所以要先去取出數組中對象
    id object = [metadataObjects lastObject];
    if ([object isKindOfClass:[AVMetadataMachineReadableCodeObject class]]) {
        NSString *stringValue;
        if ([metadataObjects count] >0) {
            AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects lastObject];
            stringValue = metadataObject.stringValue;
        }
        
        [self judgeCode:stringValue];
//        [self judgeCode:@"test00001"];
        
        [self clearLayers];
        AVMetadataMachineReadableCodeObject *obj = (AVMetadataMachineReadableCodeObject *)[self.previewLayer transformedMetadataObjectForMetadataObject:object];
        [self drawLine:obj];
    }
}
// 初始化掃描界面
-(void)initPreviewImg {
    [_output setMetadataObjectsDelegate:nil queue:dispatch_get_main_queue()];
    [_session stopRunning];
    [_session removeOutput:_output];
    [_session removeInput:_input];
    
    [_containerLayer removeFromSuperlayer];
    [_previewLayer removeFromSuperlayer];
    
    _containerLayer = nil;       //不置空,二維碼的彩色邊框無法去除
    _session = nil;                 // 不置空,返回本頁面,出現白屏
    _output = nil;
    _previewLayer = nil;        // 不置空,會有空指針,由下個界面返回時會出現崩潰
    /*
     Assertion failed: (_inputInternal->figCaptureSession == NULL), function __44-[AVCaptureInput attachToFigCaptureSession:]_block_invoke, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/EmbeddedAVFoundation/EmbeddedAVFoundation-1184.7/Aspen/AVCaptureInput.m, line 132.
     */
}

- (void)clearLayers {
    if (self.containerLayer.sublayers) {
        for (CALayer *subLayer in self.containerLayer.sublayers) {
            [subLayer removeFromSuperlayer];
        }
    }
}
#pragma mark -------- 懶載入---------
- (AVCaptureDevice *)device {
    if (_device == nil) {
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _device;
}

- (AVCaptureDeviceInput *)input {
    if (_input == nil) {
        _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    }
    return _input;
}

- (AVCaptureSession *)session {
    if (_session == nil) {
        _session = [[AVCaptureSession alloc] init];
    }
    return _session;
}

- (AVCaptureVideoPreviewLayer *)previewLayer {
    if (_previewLayer == nil) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
        _previewLayer.frame = self.view.bounds;
    }
    return _previewLayer;
}

- (AVCaptureMetadataOutput *)output {
    if (_output == nil) {
        _output = [[AVCaptureMetadataOutput alloc] init];
        CGRect viewRect = self.view.frame;
        CGRect containerRect = _scanFrame.frame;
        CGFloat x = containerRect.origin.y / viewRect.size.height;
        CGFloat y = containerRect.origin.x / viewRect.size.width;
        CGFloat width = containerRect.size.height / viewRect.size.height;
        CGFloat height = containerRect.size.width / viewRect.size.width;
        _output.rectOfInterest = CGRectMake(x, y, width, height);
    }
    return _output;
}

- (CALayer *)containerLayer {
    if (_containerLayer == nil) {
        _containerLayer = [[CALayer alloc] init];
        _containerLayer.frame = self.view.bounds;
    }
    return _containerLayer;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
創建對象

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 主要的有: 字體相關:line-height, font-family, font-size, font-style, font-variant, font-weight, font 文本相關: letter-spacing, text-align, text-indent, text-transf ...
  • 開本系列,談談一些有趣的 CSS 題目,題目類型天馬行空,想到什麼說什麼,不僅為了拓寬一下解決問題的思路,更涉及一些容易忽視的 CSS 細節。 解題不考慮相容性,題目天馬行空,想到什麼說什麼,如果解題中有你感覺到生僻的 CSS 屬性,趕緊去補習一下吧。 不斷更新,不斷更新,不斷更新,重要的事情說三遍 ...
  • $("#cbutton1").bind("click",{"id":"111","name":"aaa"},getData); 這一句給 cbutton1 指定了 click 事件的綁定函數為 getData,並且向該函數傳遞了JSON格式參數 {"id":"111", "name":"aaa"}. ...
  • var val = $("select[name='type_irb'] option:selected").val(); ...
  • 轉載請註明——博客園igoslly:http://www.cnblogs.com/igoslly/p/6833544.html 轉載請註明——博客園igoslly:http://www.cnblogs.com/igoslly/p/6833544.html 在實際方法調用中,程式按順序逐句執行,直到“ ...
  • 要點:就是緩存輸入的內容到 本地 下麵就是實現保存 搜索內容到本地 和 清空本地歷史的 方法 activity 下拉彈出layout佈局 ...
  • 我們開發中常用到圖片上傳,比如頭像上傳之類的,還有類似發佈空間說說時發佈多張圖片等等,我在這裡通過借鑒網路資源,並依賴於七牛雲存儲做了一個圖片上傳的小結。 我首先封裝了一個圖片上傳的工具類,繼承自nsobject,命名為QiniuTool;再多圖上傳時,還需要單張圖片的上傳結果處理,因此,我在這裡有 ...
  • 該View轉自 http://blog.csdn.net/Kalwang/article/details/4708721 ,感謝這位大神。 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...