標籤:swift二維碼 swift二維碼掃描 swift二維碼產生
系統提供的AVCaptureSession只適用於iOS7.0以上的系統;之前的請用Zbar來替代
:http://download.csdn.net/detail/huobanbengkui/8881097
配置工程:
引入:
import Foundation
import AVFoundation
接受AVCaptureMetadataOutputObjectsDelegate(如: class QrcodeVC: UIViewController,AVCaptureMetadataOutputObjectsDelegate, UIAlertViewDelegate)
一. 二維碼掃描
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。大家可以嘗試修改。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Swift:使用系統AVFoundation實現二維碼掃描和產生