美文网首页Swift开发技巧iOS开发基础ios开发
Swift二维码扫描实现(自定义UI)

Swift二维码扫描实现(自定义UI)

作者: 二营长意大利炮呢 | 来源:发表于2016-06-20 17:45 被阅读3944次

    前不久有网友跟我说,demo有bug不能运行,所以抽空改了一下,主要原因是swift版本问题,当初我写这个demo的时候是Swift3.0 贝塔版,所以有些语法上的更新。

    在过去的WWDC2016中,Apple Inc推出了新版Swift--Swift3.0;对于Swift3.0的语法什么的,在此就不聊了,毕竟人家还是个小白。

    Apple Inc WWDC2016

    书归正传,iOS7.0以前要使用二维码扫描功能,需要借助两大开源的组件ZBar和ZXing来实现,自iOS7.0之后可以使用自带的AVFoundation框架实现二维码扫描,而且效率更高。

    因此实现二维码扫描首先需要导入AVFoundation框架

    • 1 导入AVFoundation框架
    import AVFoundation
    
    • 2 创建视图预览显示并设置想实现的UI效果
    //屏幕扫描区域视图
     //屏幕扫描区域视图
        let barcodeView = UIView(frame: CGRect(x: UIScreen.main.bounds.size.width * 0.2, y: UIScreen.main.bounds.size.height * 0.35, width: UIScreen.main.bounds.size.width * 0.6, height: UIScreen.main.bounds.size.width * 0.6))
        //扫描线
        let scanLine = UIImageView()
        
        var scanning : String!
        var timer = Timer()
     
      override init(frame: CGRect) {
        super.init(frame: frame)
      barcodeView.layer.borderWidth = 1.0
            barcodeView.layer.borderColor = UIColor.white.cgColor
            self.addSubview(barcodeView)
            
            //设置扫描线
            scanLine.frame = CGRect(x: 0, y: 0, width: barcodeView.frame.size.width, height: 5)
            scanLine.image = UIImage(named: "QRCodeScanLine")
            
            //添加扫描线图层
            barcodeView.addSubview(scanLine)
            
            self.createBackGroundView()
            
            self.addObserver(self, forKeyPath: "scanning", options: .new, context: nil)
            
            timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(moveScannerLayer(_:)), userInfo: nil, repeats: true)
      }
    
    • 3 实现背景灰色半透明,分四个View,设置所需要实现的样式;同样的也可以采用重写drawRect方法来实现。
    func createBackGroundView() {
       let topView = UIView(frame: CGRect(x: 0, y: 0,  width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height * 0.35))
            let bottomView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.width * 0.6 + UIScreen.main.bounds.size.height * 0.35, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height * 0.65 - UIScreen.main.bounds.size.width * 0.6))
            
            let leftView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height * 0.35, width: UIScreen.main.bounds.size.width * 0.2, height: UIScreen.main.bounds.size.width * 0.6))
            let rightView = UIView(frame: CGRect(x: UIScreen.main.bounds.size.width * 0.8, y: UIScreen.main.bounds.size.height * 0.35, width: UIScreen.main.bounds.size.width * 0.2, height: UIScreen.main.bounds.size.width * 0.6))
            
            topView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
            bottomView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
            leftView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
            rightView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
            
            let label = UILabel(frame: CGRect(x: 0, y: 10, width: UIScreen.main.bounds.size.width, height: 21))
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: 14)
            label.textColor = UIColor.white
            label.text = "将二维码/条形码放入扫描框内,即自动扫描"
            
            bottomView.addSubview(label)
            
            
            self.addSubview(topView)
            self.addSubview(bottomView)
            self.addSubview(leftView)
            self.addSubview(rightView)
      }
    
    • 4 在初始化视图的时候添加观察者,用于实现暂停扫描时,扫描线停止滚动
    self.addObserver(self, forKeyPath: "scanning", options: .new, context: nil)
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            
            if scanning == "start" {
                timer.fire()
            }else{
                timer.invalidate()
            }
        }
    
    • 5 扫描线滚动动画
    //让扫描线滚动
      func moveScannerLayer(_ timer : Timer) {
        scanLine.frame = CGRect(x: 0, y: 0, width: self.barcodeView.frame.size.width, height: 12)
        UIView.animate(withDuration: 2) {
          self.scanLine.frame = CGRect(x: self.scanLine.frame.origin.x, y: self.scanLine.frame.origin.y + self.barcodeView.frame.size.height - 10, width: self.scanLine.frame.size.width, height: self.scanLine.frame.size.height) 
        }
      }
    
    • 6 声明背景视图
    //相机显示视图
        let cameraView = ScannerBackgroundView(frame: UIScreen.main.bounds)
    
    • 7 初始化捕捉设备、创建捕捉会话、输入媒体类型、设置代理等
        let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
       
        let input :AVCaptureDeviceInput
       
        let output = AVCaptureMetadataOutput()
       
        //捕捉异常,并处理异常
        do{
          input = try AVCaptureDeviceInput(device: captureDevice)
          captureSession.addInput(input)
          captureSession.addOutput(output)
        }catch {
          print("异常")
        }
        let dispatchQueue = DispatchQueue(label: "queue", attributes: [])
        output.setMetadataObjectsDelegate(self, queue: dispatchQueue)
        output.metadataObjectTypes = NSArray(array: [AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]) as [AnyObject]
        let videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
       
        videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
       
        videoPreviewLayer?.frame = cameraView.bounds
       
        cameraView.layer.insertSublayer(videoPreviewLayer!, at: 0)
    
        output.rectOfInterest = CGRect(x: 0.2, y: 0.2, width: 0.6, height: 0.6)
    
    • 8 扫描结果处理(根据不同扫描结果,执行不同的操作)
     if metadataObjects != nil && metadataObjects.count > 0 {
                let metaData : AVMetadataMachineReadableCodeObject = metadataObjects.first as! AVMetadataMachineReadableCodeObject
                
                print(metaData.stringValue)
                
                DispatchQueue.main.async(execute: {
                    let result = WebViewController()
                    result.url = metaData.stringValue
                    
                    self.navigationController?.pushViewController(result, animated: true)
                })
                captureSession.stopRunning()
            }
    
    • 9 从相册中获取二维码图片进行识别,在此需要判断相册中获取的图片是否具有二维码信息
    let image = info[UIImagePickerControllerOriginalImage]
       
        let imageData = UIImagePNGRepresentation(image as! UIImage)
       
        let ciImage = CIImage(data: imageData!)
       
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyLow])
       
        let array = detector?.features(in: ciImage!)
       
        let result : CIQRCodeFeature = array!.first as! CIQRCodeFeature
       
       
        let resultView = WebViewController()
        resultView.url = result.messageString
       
        self.navigationController?.pushViewController(resultView, animated: true)
        picker.dismiss(animated: true, completion: nil)
    

    欧了,所有工作都已完成;由于本人是个菜鸟,思路仅供参考,如果有更好的思路,欢迎交流。
    附上:
    demo地址:demo下载

    相关文章

      网友评论

      本文标题:Swift二维码扫描实现(自定义UI)

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