您的位置:首页 > 移动开发 > Swift

iOS生成二维码(中间包含图片),长按识别二维码(Swift)

2016-08-17 18:01 471 查看
在iOS中有个类CIFilter,通过这个类可以创建各种特定的过滤器,今天我们主要介绍一种二维码发生器(CIQRCodeGenerator)滤镜,通过这个滤镜可以自动生成我们需要的二维码。

首先我们要创建一个二维码滤镜:

//创建二维码滤镜
let qrCIFilter = CIFilter(name: "CIQRCodeGenerator")


注意,这个初始化方法中的传入参数是只有固定的几种字符串的,使用不同的字符串可以创建不同用处的滤镜的。所以在官方的参考文档中特别说明在创建以后要检查qrCIFilter是否为空,以防拼写错误无法创建滤镜。如果我们想知道到底有哪几种固定的字符串可以在Xcode中command+右键点击CIQRCodeGenerator字符串,跳到的参考文献上下文中有其他固定值的介绍的。

滤镜创建出来了,我们还要给这滤镜添加各种属性,滤镜的属性是一对一对的键值对的,同样的这个属性字典的key值也是固定的,二维码滤镜有两种属性inputMessage和inputCorrectionLevel,在iOS中,滤镜的属性如果你不特别设置那么系统会给一个默认值,所以你无需再统一设置默认值。inputMessage指输入信息,具体来说就是你要加密的的字符串,但是value值是NSData类型的,inputCorrectionLevel指输入的纠错级别,有四种不同的级别:A single letter specifying the error correction format. An NSString object whose display name is CorrectionLevel不多说了,看代码:

//二维码包含的信息
qrCIFilter!.setValue(messageData, forKey: "inputMessage")
//L7% M15% Q25% H%30% 纠错级别. 默认值是M
qrCIFilter!.setValue("H", forKey: "inputCorrectionLevel")


到这一步其实你已经创建了一个最简单的二维码了,你可以输出过滤后的图片了:

let qrImage = qrCIFilter?.outputImage


这里qrImage是CIImage类型的,你可以通过这个qrImage创建一个UIImage类型的图片,然后放到UIImageView视图显示出来,但是你会发现这个二维码会非常模糊,我们要对它进一步处理。

在这里先感谢一下航哥的无私奉献,下面的处理我也是看到他的分享后才知道可以这么做的。我们在上面的基础上再创建一个滤镜CIFalseColor,我查了下官方文档度这种滤镜的说明简单:False color is often used to process astronomical and other scientific data, such as ultraviolet and x-ray images,其实它的用处是用来伪造颜色的。CIFalseColor只有三个固定的属性inputImage,inputColor0,inputColor1。这三属性很好理解,直接看代码:

let colorFilter = CIFilter(name: "CIFalseColor")
//输入图片
colorFilter!.setValue(qrImage, forKey: "inputImage")
//输入颜色
colorFilter!.setValue(CIColor(red: 0,green: 0,blue: 0), forKey: "inputColor0")
colorFilter!.setValue(CIColor(red: 1,green: 1,blue: 1), forKey: "inputColor1")


然后我们再对图片进行缩放(缩放后图片会很清晰),并且转换成UIImage类型:

var image = UIImage(CIImage: colorFilter!.outputImage!
.imageByApplyingTransform(CGAffineTransformMakeScale(5, 5)))


到这里我们的二维码图片已经生成完毕了,但是我们常常会在二维码中间放置图片来做个性化处理。这个就相当于在图片中再添加一个图片,处理起来就比较简单了,其实就四个步骤:第一开启上下文;第二图片重绘这里我们要重绘两张图片一张是二维码图片一张是个性化图片;第三是通过上下文获取图片;第三是关闭上下文。

//开启上下文
UIGraphicsBeginImageContext(frame.size)
//二维码图片重绘(二维码图片如果不绘制,获取的图片无法反过来创建CIImage)
image.drawInRect(frame)
if let myImage = UIImage(named:andImageName) {
//个性图片尺寸
let mySize = CGSizeMake(frame.size.width/4, frame.size.height/4)
//重绘自定义图片
myImage.drawInRect(CGRectMake(frame.size.width/2-mySize.width/2, frame.size.height/2-mySize.height/2, mySize.width, mySize.height))
}
//从上下文获取图片
image = UIGraphicsGetImageFromCurrentImageContext()
//关闭上下文
UIGraphicsEndImageContext()


下面我们再看看二维码的识别,先创建一个长按手势:

let longTap = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
self.view .addGestureRecognizer(longTap)


然后当长按时我们解析我们的二维码。解析二维码要创建探测器,探测器有不同的类型,这里创建一个简单的二维码探测器。

创建探测器有几个传入参数:探测器类型、上下文、属性选项:

/*创建探测器 options 是字典key:
CIDetectorAccuracy 精度
CIDetectorTracking 轨迹
CIDetectorMinFeatureSize 最小特征尺寸
CIDetectorNumberOfAngles 角度**/
let dector = CIDetector(ofType: CIDetectorTypeQRCode, context: CIContext(), options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])


然后我们再创建一个CIImage类型的图片,探测器会探测出这张图片里面的所有二维码:

let qrFeatures = dector.featuresInImage(decodeImage!) as! [CIQRCodeFeature]


上面的代码中qrFeatures值是一个数组,元素类型是CIQRCodeFeature(二维码特征),CIQRCodeFeature有个属性messageString表示二维码所代表的信息。

怎么样长按识别二维码是不是很简单。下面的是整个demo的源码,有兴趣的可以参考下:

//
// ViewController.swift
// 通过滤镜CIFilter生成二维码
//
// Created by 句芒 on 16/8/17.
// Copyright © 2016年 fanwei. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

let imageView = UIImageView(frame: CGRect(x: 30, y: 50, width: 200, height: 200))
let pictureView = UIImageView(frame: CGRect(x: 50, y: 270, width: 200, height: 200))

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

imageView.image = createQRCodeByCIFilterWithString("句芒二维码发生器", andImageName:"")

self.view .addSubview(imageView)

pictureView.image = createQRCodeByCIFilterWithString("http://www.jubaobar.com", andImageName: "jubaobar.jpg")
self.view.addSubview(pictureView)

let longTap = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
self.view .addGestureRecognizer(longTap)
let data = UIImagePNGRepresentation(pictureView.image!)
let path = NSHomeDirectory().stringByAppendingString("/Documents/s.png")
data!.writeToFile(path, atomically: true)
print(path)
}

func longPress(recoginzer:UILongPressGestureRecognizer) {
let point = recoginzer.locationInView(self.view)
if imageView.frame.contains(point) {
return show(decodeQRCode(imageView.image!))
}
if pictureView.frame.contains(point) {

return show(decodeQRCode(pictureView.image!))
}
}

func decodeQRCode(image:UIImage) -> String {
let decodeImage = CIImage(image: image)
/*创建探测器 options 是字典key:
CIDetectorAccuracy 精度
CIDetectorTracking 轨迹
CIDetectorMinFeatureSize 最小特征尺寸
CIDetectorNumberOfAngles 角度**/
let dector = CIDetector(ofType: CIDetectorTypeQRCode, context: CIContext(), options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])

let qrFeatures = dector.featuresInImage(decodeImage!) as! [CIQRCodeFeature]
return qrFeatures.last!.messageString

}

func show(message:String) {
let alert = UIAlertController(title: "二维码", message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "知道了", style:.Cancel, handler: nil))
self .presentViewController(alert, animated: true, completion: nil)
}

func createQRCodeByCIFilterWithString(message:String,andImageName:String) -> UIImage? {
if let messageData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
//创建二维码滤镜
let qrCIFilter = CIFilter(name: "CIQRCodeGenerator")
//二维码包含的信息
qrCIFilter!.setValue(messageData, forKey: "inputMessage")
//L7% M15% Q25% H%30% 纠错级别. 默认值是M
qrCIFilter!.setValue("H", forKey: "inputCorrectionLevel")
let qrImage = qrCIFilter?.outputImage
//创建颜色滤镜主要是了解决二维码不清晰 False color is often used to process astronomical and other scientific data, such as ultraviolet and x-ray images.通常用于处理紫外线,x射线等天文或科学的数据
let colorFilter = CIFilter(name: "CIFalseColor")
//输入图片
colorFilter!.setValue(qrImage, forKey: "inputImage")
//输入颜色
colorFilter!.setValue(CIColor(red: 0,green: 0,blue: 0), forKey: "inputColor0")
colorFilter!.setValue(CIColor(red: 1,green: 1,blue: 1), forKey: "inputColor1")
var image = UIImage(CIImage: colorFilter!.outputImage! .imageByApplyingTransform(CGAffineTransformMakeScale(5, 5)))
let frame = CGRectMake(0, 0, image.size.width, image.size.height)

//开启上下文
UIGraphicsBeginImageContext(frame.size)
//二维码图片重绘(二维码图片如果不绘制,获取的图片无法反过来创建CIImage)
image.drawInRect(frame)
if let myImage = UIImage(named:andImageName) {
//个性图片尺寸
let mySize = CGSizeMake(frame.size.width/4, frame.size.height/4)
//重绘自定义图片
myImage.drawInRect(CGRectMake(frame.size.width/2-mySize.width/2, frame.size.height/2-mySize.height/2, mySize.width, mySize.height))
}
//从上下文获取图片
image = UIGraphicsGetImageFromCurrentImageContext()
//关闭上下文
UIGraphicsEndImageContext()

return image
}
return nil
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息