扫一扫二维码

作者: 楓葉乄神無月 | 来源:发表于2016-11-25 20:50 被阅读9次
import UIKit
import AVFoundation

class RichScanViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
    
    var captureDevice: AVCaptureDevice?
    var captureSession:AVCaptureSession?
    var videoPreviewLayer:AVCaptureVideoPreviewLayer?
    var qrCodeFrameView:UIView?
    var scanLayer:CALayer!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "开灯", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(clickRightBtn))

        initView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: - 自定义方法
    func initView(){
        captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do{
            let input = try AVCaptureDeviceInput(device: captureDevice)
            captureSession = AVCaptureSession()
            captureSession?.addInput(input as AVCaptureInput)
            let captureMetadataOutput = AVCaptureMetadataOutput()
            captureSession?.addOutput(captureMetadataOutput)
            captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
            captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
            
            // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
            videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
            videoPreviewLayer?.frame = view.layer.bounds
            view.layer.addSublayer(videoPreviewLayer!)
            
            // Initialize QR Code Frame to highlight the QR code
            qrCodeFrameView = UIView(frame: CGRectMake((screen_width - screen_width * 0.66) / 2, top_height + (screen_height - top_height - screen_width * 0.66) / 2, screen_width * 0.66, screen_width * 0.66))
            qrCodeFrameView?.layer.borderColor = UIColor.whiteColor().CGColor
            qrCodeFrameView?.layer.borderWidth = 2
            view.addSubview(qrCodeFrameView!)
            view.bringSubviewToFront(qrCodeFrameView!)
            
            // Start video capture.
            captureSession?.startRunning()
        }catch{
            print("扫一扫初始化失败~")
        }
        
        let descLbl1 = UILabel(frame: CGRectMake(0, (qrCodeFrameView?.frame.origin.y)! - 15 - 17 - 5 - 17, screen_width, 17));
        descLbl1.textColor = UIColor.whiteColor()
        descLbl1.textAlignment = NSTextAlignment.Center
        descLbl1.text = "将取景框对准二维码"
        view.addSubview(descLbl1)
        
        let descLbl2 = UILabel(frame: CGRectMake(0, (qrCodeFrameView?.frame.origin.y)! - 15 - 17, screen_width, 17));
        descLbl2.textColor = UIColor.whiteColor()
        descLbl2.textAlignment = NSTextAlignment.Center
        descLbl2.text = "即可自动扫描"
        view.addSubview(descLbl2)
        
        initScanLine()
    }
    
    func clickRightBtn(){
        do{
            //锁定设备以便进行手电筒状态修改
            try captureDevice?.lockForConfiguration()
            if captureDevice?.torchMode == AVCaptureTorchMode.Off{
                //设置手电筒模式为亮灯(On)
                captureDevice?.torchMode = AVCaptureTorchMode.On
                //改变按钮标题
                self.navigationItem.rightBarButtonItem?.title = "关灯"
            }else{
                //设置手电筒模式为关灯(Off)
                captureDevice?.torchMode = AVCaptureTorchMode.Off
                //改变按钮标题
                self.navigationItem.rightBarButtonItem?.title = "开灯"
            }
            //解锁设备锁定以便其他APP做配置更新
            captureDevice?.unlockForConfiguration()
        }catch{
            return;
        }
    }
    
    func initScanLine() {
        scanLayer = CALayer();
        scanLayer.frame = CGRectMake(0, 0, qrCodeFrameView!.bounds.size.width, 1);
        scanLayer.backgroundColor = UIColor.grayColor().CGColor
        qrCodeFrameView?.layer.addSublayer(scanLayer)
        let timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: #selector(moveScanLayer(_:)), userInfo: nil, repeats: true)
        timer.fire()
    }
    
    func moveScanLayer(timer: NSTimer){
        var frame = scanLayer.frame
        if qrCodeFrameView?.frame.size.height < scanLayer.frame.origin.y {
            scanLayer.hidden = true
            frame.origin.y = 0
            scanLayer.frame = frame
        }else{
            scanLayer.hidden = false
            frame.origin.y += 5
            UIView.animateWithDuration(0.1, animations: { 
                self.scanLayer.frame = frame
            })
        }
    }
    
    //MARK: - AVCaptureMetadataOutputObjectsDelegate
    func captureOutput(captureOutput: AVCaptureOutput!,
                       didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection
        connection: AVCaptureConnection!) {
        
        // Check if the metadataObjects array is not nil and it contains at least one object.
        if metadataObjects == nil || metadataObjects.count == 0 {
            print("No QR code is detected")
            return
        }
        
        // Get the metadata object.
        let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
        if metadataObj.type == AVMetadataObjectTypeQRCode {
            if metadataObj.stringValue != nil {
                UIApplication.sharedApplication().openURL(NSURL(string: metadataObj.stringValue)!)
            }
        }
    }
    
}

相关文章

网友评论

    本文标题:扫一扫二维码

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