二维码

2016-03-07  本文已影响69人  河小龙

QR: Quick Response

QR Code Reader

概略

<center>



</center>
以AVCaptureSession为核心,指定Input和Output,其中

使用步骤

1. import AVFoundation

2. 协议AVCaptureMetadataOutputObjectsDelegate

3. Input

let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession = AVCaptureSession()
captureSession?.addInput(input)

4. Output

let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]

5. Previewer

videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
localView.layer.addSublayer(videoPreviewLayer!)
videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer?.frame = CGRectMake(0, 0, localView.frame.width, localView.frame.height)

6. delegate method:

// MARK: delegate methods

func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
    
    if metadataObjects == nil || metadataObjects.count == 0 {
        qrCodeFrameView?.frame = CGRectZero
        textField.text = "No QR Code is detected"
        return
    }
    
    let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
    
    if metadataObj.type == AVMetadataObjectTypeQRCode {
        let barCodeObj = (videoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadataObj))! as AVMetadataObject
        qrCodeFrameView?.frame = barCodeObj.bounds
        
        if metadataObj.stringValue != nil {
            textField.text = metadataObj.stringValue
        }
        captureSession?.stopRunning()
        qrBtn.setTitle("Start", forState: UIControlState.Normal)
    }
}

效果图

<center>



</center>

QR Code Generator

概略

<center>



</center>
以CIFilter为核心,设置:

使用步骤

1. 编码数据

let data = textField.text?.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)

2. 设置CIFilter

let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue("Q", forKey: "inputCorrectionLevel") // "Q", 25%

3. Output

qrcodeImage = filter?.outputImage

4. 缩放outputImage

let transformedImage = qrcodeImage.imageByApplyingTransform(CGAffineTransformMakeScale(scaleX, scaleY))

效果图

<center>



</center>

上一篇下一篇

猜你喜欢

热点阅读