美文网首页
swift 二维码扫描

swift 二维码扫描

作者: kys攻城狮s | 来源:发表于2016-04-08 11:57 被阅读71次
    //MARK: 初始化二维码扫描器
        func initQRCodeScaner(){
            // 获取 AVCaptureDevice 实例
            _captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
            // 初始化输入流
            do{
                try _inputStream = AVCaptureDeviceInput(device: _captureDevice!)
            }catch{
                print("初始化输入流 with device 失败")
            }
            if _inputStream == nil{
                return
            }
            _ctr._isScaning = true
            // 创建会话
            _captureSession = AVCaptureSession()
            _captureSession?.addInput(_inputStream)
            // 初始化输出流
            _captureMetadataOutput = AVCaptureMetadataOutput()
            //设置区域
            //CGRectMake(y的起点/屏幕的高,x的起点/屏幕的宽,扫描的区域的高/屏幕的高,扫描的区域的宽/屏幕的宽)
            _captureMetadataOutput?.rectOfInterest = CGRect(x: _scanRect!.origin.y/kScreenHeight, y: _scanRect!.origin.x/kScreenWidth, width: _scanRect!.height / kScreenHeight, height: _scanRect!.width / kScreenWidth)
            // 添加输出流
            _captureSession?.addOutput(_captureMetadataOutput)
            // 创建dispatch queue.
            let dispatchQueue = dispatch_queue_create(kScanQRCodeQueueName, nil)
            _captureMetadataOutput?.setMetadataObjectsDelegate(self, queue: dispatchQueue)
            // 设置元数据类型 AVMetadataObjectTypeQRCode
            let objArray = NSArray(objects: AVMetadataObjectTypeQRCode)
            _captureMetadataOutput?.metadataObjectTypes = objArray as [AnyObject]
            // 创建输出对象
            _videoPreviewLayer = AVCaptureVideoPreviewLayer(session: _captureSession)
            _videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
            _videoPreviewLayer?.frame = self.view.bounds
            self.view.layer.insertSublayer(_videoPreviewLayer!, atIndex: 0)
    
        }
    

    相关文章

      网友评论

          本文标题:swift 二维码扫描

          本文链接:https://www.haomeiwen.com/subject/nasvlttx.html