• Swift:使用系统AVFoundation实现二维码扫描和生成


    系统提供的AVCaptureSession仅仅适用于iOS7.0以上的系统。之前的请用Zbar来替代

    下载地址:http://download.csdn.net/detail/huobanbengkui/8881097

    配置project:

    引入:

    import Foundation
    import AVFoundation

    接受AVCaptureMetadataOutputObjectsDelegate(如: class QrcodeVC: UIViewController,AVCaptureMetadataOutputObjectsDelegate, UIAlertViewDelegate)

    定义属性:

        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        let session = AVCaptureSession()
        var layer: AVCaptureVideoPreviewLayer?

    一. 二维码扫描

    1.使用相机捕捉二维码

    func setupCamera(){
            self.session.sessionPreset = AVCaptureSessionPresetHigh
            var error : NSError?
            let input = AVCaptureDeviceInput(device: device, error: &error)
            if (error != nil && input == nil) {
                var errorAlert = UIAlertView(title: "提醒", message: "请在iPhone的"设置-隐私-相机"选项中,同意本程序訪问您的相机", delegate: self, cancelButtonTitle: "确定")
                    errorAlert.show()
                return
            }
            if session.canAddInput(input) {
                session.addInput(input)
            }
            layer = AVCaptureVideoPreviewLayer(session: session)
            layer!.videoGravity = AVLayerVideoGravityResizeAspectFill
            //能够看到的镜头区域
            layer!.frame = CGRectMake(0, 0,320,568)
            self.view.layer.insertSublayer(self.layer, atIndex: 0)
            
            let output = AVCaptureMetadataOutput()
            //设置响应区域
            //        output.rectOfInterest = CGRectMake(0, 0, 0, 0)
            output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
            if session.canAddOutput(output) {
                session.addOutput(output)
                output.metadataObjectTypes = [AVMetadataObjectTypeQRCode];
            }
            
            session.startRunning()
        }

    2.识别二维码以后,解析数据(实现AVCaptureMetadataOutputObjectsDelegate的代理方法)

    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
            
            var stringValue:String?
            if metadataObjects.count > 0 {
                var metadataObject = metadataObjects[0] as!AVMetadataMachineReadableCodeObject
                stringValue = metadataObject.stringValue
                
                if stringValue != nil{
                    self.session.stopRunning()
                    
                    
                }
            }
            self.session.stopRunning()
            var alertView = UIAlertView(title: "二维码", message: stringValue, delegate: self, cancelButtonTitle: "确定")
            alertView.show()
        }

    最后在页面消失的时候:

    override func viewWillDisappear(animated: Bool) {
            super.viewWillDisappear(animated)
            
            if self.session.running {
                self.session.stopRunning()
            }
        }

    二. 二维码生成

    func createQRForString(qrString: String?, qrImageName: String?) -> UIImage?{
            if let sureQRString = qrString {
                let stringData = sureQRString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
                // 创建一个二维码的滤镜
                let qrFilter = CIFilter(name: "CIQRCodeGenerator")
                qrFilter.setValue(stringData, forKey: "inputMessage")
                qrFilter.setValue("H", forKey: "inputCorrectionLevel")
                let qrCIImage = qrFilter.outputImage
                // 创建一个颜色滤镜,黑白色
                let colorFilter = CIFilter(name: "CIFalseColor")
                colorFilter.setDefaults()
                colorFilter.setValue(qrCIImage, forKey: "inputImage")
                colorFilter.setValue(CIColor(red: 0, green: 0, blue: 0), forKey: "inputColor0")
                colorFilter.setValue(CIColor(red: 1, green: 1, blue: 1), forKey: "inputColor1")
                // 返回二维码image
                let codeImage = UIImage(CIImage: colorFilter.outputImage.imageByApplyingTransform(CGAffineTransformMakeScale(5, 5)))
                // 通常,二维码都是定制的,中间都会放想要表达意思的图片
                if let iconImage = UIImage(named: qrImageName!) {
                    let rect = CGRectMake(0, 0, codeImage!.size.width, codeImage!.size.height)
                    UIGraphicsBeginImageContext(rect.size)
                    
                    codeImage!.drawInRect(rect)
                    let avatarSize = CGSizeMake(rect.size.width * 0.25, rect.size.height * 0.25)
                    let x = (rect.width - avatarSize.width) * 0.5
                    let y = (rect.height - avatarSize.height) * 0.5
                    iconImage.drawInRect(CGRectMake(x, y, avatarSize.width, avatarSize.height))
                    let resultImage = UIGraphicsGetImageFromCurrentImageContext()
                    
                    UIGraphicsEndImageContext()
                    return resultImage
                }
                return codeImage
            }
            return nil
        }

    怎样使用呢??

    var imageViewIcon = UIImageView(frame: CGRectMake(100, 100, 150, 150))
            imageViewIcon.image = createQRForString("好好", qrImageName: "ocrBack") //“ocrBack” 放入二维码中间图片的名字
            self.view.addSubview(imageViewIcon)

    如图:

    最后说明:

    AVFoundation框架不仅支持二维码扫描。还支持非常多别的条码类别。比如Code39,Code128,Aztec,和PDF417。大家能够尝试改动。


  • 相关阅读:
    人间故事馆话题:聊聊那些被骗经历,让其他人不再被骗
    路过的风景
    路过的风景
    上海最适合拍照的旅游地点
    Java EE (11)
    五、服务器端的局域网
    P1294 高手去散步 洛谷
    堆排序【模板】
    P3383 【模板】线性筛素数 洛谷
    P1516 青蛙的约会 洛谷
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5202011.html
Copyright © 2020-2023  润新知