iOS原生二维码扫描

释放双眼,带上耳机,听听看~!
#import "CZGQRScanViewController.h"

#import <AVFoundation/AVFoundation.h>

/**

 *  屏幕高宽边界

 */

#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#define SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width

#define SCREEN_BOUNDS  [UIScreen mainScreen].bounds

#define TOP (SCREEN_HEIGHT-220)/2

#define LEFT (SCREEN_WIDTH-220)/2

#define kScanRect CGRectMake(LEFT, TOP, 220,
220)

@interface
CZGQRScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>{

    int num;

    BOOL upOrdown;

    NSTimer * timer;

    CAShapeLayer *cropLayer;

}

@property (strong,nonatomic)AVCaptureDevice
* device;

@property (strong,nonatomic)AVCaptureDeviceInput
* input;

@property (strong,nonatomic)AVCaptureMetadataOutput
* output;

@property (strong,nonatomic)AVCaptureSession
* session;

@property (strong,nonatomic)AVCaptureVideoPreviewLayer
* preview;




@property (nonatomic,
strong) UIImageView * line;




@end


@implementation CZGQRScanViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    [selfconfigView];

    [selfsetNaviForUI];

}

#pragma mark - <UI界面>

- (void)setNaviForUI

{

    //1.标题

    self.title =@"二维码扫描";

    //2.返回按钮

    UIButton *cancelBtn = [[UIButtonalloc]initWithFrame:CGRectMake(0,0, 24,24)];

    [cancelBtn setImage:[UIImageimageNamed:@"main_back"]
forState:UIControlStateNormal];

    [cancelBtn addTarget:selfaction:@selector(cancelBtnClick)
forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *cancelItem = [[UIBarButtonItemalloc]initWithCustomView:cancelBtn];

    self.navigationItem.leftBarButtonItem = cancelItem;  

}

-(void)configView{

    UIImageView * imageView = [[UIImageViewalloc]initWithFrame:kScanRect];

    imageView.image = [UIImageimageNamed:@"pick_bg"];

    [self.viewaddSubview:imageView];

    

    upOrdown =NO;

    num =0;

    _line = [[UIImageViewalloc] initWithFrame:CGRectMake(LEFT,TOP+10,220,2)];

    _line.image = [UIImageimageNamed:@"line.png"];

    [self.viewaddSubview:_line];

    timer = [NSTimerscheduledTimerWithTimeInterval:.02target:selfselector:@selector(animation1)
userInfo:nilrepeats:YES];


}

-(void)viewWillAppear:(BOOL)animated{

    [selfsetCropRect:kScanRect];

    [selfperformSelector:@selector(setupCamera)
withObject:nilafterDelay:0.3];

}


-(void)animation1

{

    if (upOrdown ==NO) {

        num ++;

        _line.frame =CGRectMake(LEFT,TOP+10+2*num,220, 2);

        if (2*num ==200) {

            upOrdown =YES;

        }

    }

    else {

        num --;

        _line.frame =CGRectMake(LEFT,TOP+10+2*num,220, 2);

        if (num ==0) {

            upOrdown =NO;

        }

    }

    

}


- (void)setCropRect:(CGRect)cropRect{

    cropLayer = [[CAShapeLayeralloc] init];

    CGMutablePathRef path =CGPathCreateMutable();

    CGPathAddRect(path,nil, cropRect);

    CGPathAddRect(path,nil, self.view.bounds);
 

    [cropLayersetFillRule:kCAFillRuleEvenOdd];

    [cropLayersetPath:path];

    [cropLayersetFillColor:[UIColorblackColor].CGColor];

    [cropLayersetOpacity:0.6];

    [cropLayersetNeedsDisplay];


    [self.view.layeraddSublayer:cropLayer];

}

- (void)setupCamera

{

    AVCaptureDevice *device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];

    if (device==nil) {

        UIAlertController *alert = [UIAlertControlleralertControllerWithTitle:@"提示"message:@"设备没有摄像头"preferredStyle:UIAlertControllerStyleAlert];

        [alert addAction:[UIAlertActionactionWithTitle:@"确认"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction *
_Nonnull action) {


        }]];

        [selfpresentViewController:alert animated:YES completion:nil];

        return;

    }

    // Device

    _device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];

    

    // Input

    _input = [AVCaptureDeviceInputdeviceInputWithDevice:self.deviceerror:nil];

    

    // Output

    _output = [[AVCaptureMetadataOutputalloc]init];

    [_outputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];

    

    //设置扫描区域

    CGFloat top =TOP/SCREEN_HEIGHT;

    CGFloat left =LEFT/SCREEN_WIDTH;

    CGFloat width =220/SCREEN_WIDTH;

    CGFloat height =220/SCREEN_HEIGHT;

    ///top 与 left互换  width与 height互换

    [_outputsetRectOfInterest:CGRectMake(top,left, height, width)];


    // Session

    _session = [[AVCaptureSessionalloc]init];

    [_sessionsetSessionPreset:AVCaptureSessionPresetHigh];

    if ([_sessioncanAddInput:self.input])

    {

        [_sessionaddInput:self.input];

    }

    

    if ([_sessioncanAddOutput:self.output])

    {

        [_sessionaddOutput:self.output];

    }

    

    // 条码类型 AVMetadataObjectTypeQRCode

    [_outputsetMetadataObjectTypes:[NSArrayarrayWithObjects:AVMetadataObjectTypeQRCode,
nil]];

    

    // Preview

    _preview =[AVCaptureVideoPreviewLayerlayerWithSession:_session];

    _preview.videoGravity =AVLayerVideoGravityResizeAspectFill;

    _preview.frame =self.view.layer.bounds;

    [self.view.layer insertSublayer:_previewatIndex:0];

    

    // Start

    [_sessionstartRunning];

}




#pragma mark AVCaptureMetadataOutputObjectsDelegate  扫描成功后的回调方法

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray
*)metadataObjects fromConnection:(AVCaptureConnection *)connection

{

    NSString *stringValue;

    

    if ([metadataObjects
count] >0)

    {

        //停止扫描

        [_sessionstopRunning];

        [timersetFireDate:[NSDatedistantFuture]];

        

        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects
objectAtIndex:0];

        stringValue = metadataObject.stringValue;

        NSLog(@"扫描结果:%@",stringValue);


        NSArray *arry = metadataObject.corners;

        for (id temp
in arry) {

            NSLog(@"%@",temp);

        }


        UIAlertController *alert = [UIAlertControlleralertControllerWithTitle:@"扫描结果"message:stringValue
preferredStyle:UIAlertControllerStyleAlert];

        [alert addAction:[UIAlertActionactionWithTitle:@"重新扫描"style:UIAlertActionStyleCancelhandler:nil]];

        [alert addAction:[UIAlertActionactionWithTitle:@"确认"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction *
_Nonnull action) {

            if (_session !=nil && timer !=nil) {

                [self.delegateCZG_QRCodeScanClick:stringValue];

                [self.navigationControllerpopViewControllerAnimated:YES];

            }else{

                [_sessionstartRunning];

                [timersetFireDate:[NSDatedate]];

            }


        }]];

        [selfpresentViewController:alert
animated:YEScompletion:nil];

        

    } else {

        NSLog(@"无扫描信息");

        return;

    }


}

#pragma mark - <按钮点击事件>

- (void)cancelBtnClick

{

    [self.navigationControllerpopViewControllerAnimated:YES];

}


@end


 

人已赞赏
iOS文章

iOS 史上最全的iOS之UITextView实现placeHolder占位文字的N种方法

2020-3-30 10:03:02

iOS文章

iOS 图片上传使用base64或者二进制流上传头像

2020-3-30 12:02:00

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索