• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

系统提供的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。大家能够尝试改动。



鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
swift中手势的使用发布时间:2022-07-13
下一篇:
iOS-Swift中的递增(++)和递减(--)被取消的原因发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap