用Swift 3.0写的微博,实现了二维码的生成,扫描与识别
项目已上传Github Github传送门
代码已封装好,直接将HZQRCodeTool
文件夹加到工程中即可,使用参考GitHub项目即可
二维码生成(带前景图片)
核心代码如下
class func generatorQRCode(input: String,
center: UIImage?) -> UIImage {
// 1.创建二维码滤镜
let filter = CIFilter(name: "CIQRCodeGenerator")
// 1.1.回复滤镜默认设置
filter?.setDefaults()
// 2.设置滤镜输入数据
let data = input.data(using: .utf8)
// KVC
filter?.setValue(data, forKey: "inputMessage")
// 2.1.设置二维码的纠错率
/*
L水平: 7%的字码可被修正
M水平: 15%的字码可被修正
Q水平: 25%的字码可被修正
H水平: 30%的字码可被修正
*/
filter?.setValue("M", forKey: "inputCorrectionLevel")
// 3.从二维码滤镜里面, 获取结果图片
guard var image = filter?.outputImage else {
print("生成失败")
return UIImage()
}
// 3.1.图片处理
let transform = CGAffineTransform.init(scaleX: 20, y: 20)
image = image.applying(transform)
var resultImage = UIImage(ciImage: image)
// 3.2.前景图片
if center != nil {
resultImage = getNewImage(source: resultImage, center: center!)
}
return resultImage
}
二维码扫描 可同时识别多个二维码
核心代码,自己封装了一个类,具体代码可见GitHub项目.
HZQRCodeTool.shared.startScan(inView: view,
isDrawCodeFrameFlag: true)
{ [weak self] (resultStrs) in
var resultMessage = resultStrs.description
if resultStrs.count == 0 {
resultMessage = "未识别到二维码"
}
let alert = UIAlertController(title: "识别结果", message: resultMessage, preferredStyle: .alert)
let action = UIAlertAction(title: "关闭", style: .cancel, handler: nil)
alert.addAction(action)
self?.present(alert, animated: true, completion: nil)
}
读取图片中二维
核心代码
/// 识别图片中的二维码
///
/// - Parameters:
/// - image: 原始图片
/// - isDrawQRCodeFrame: 是否需要绘制描边框,默认为 false
/// - Returns: 元祖(结果字符串组成的数组, 绘制好二维码边框的图片(如果不要求绘制,则返回原始图片))
class func detectorQCodeImage(image: UIImage,
isDrawQRCodeFrame: Bool = false) -> (resultStrs: [String], resultImage: UIImage) {
guard let imageCi = CIImage(image: image) else {
return ([], image)
}
// 1.开始识别
// 1.1.创建一个二维码探测器
let detector = CIDetector(ofType: CIDetectorTypeQRCode,
context: nil,
options: [CIDetectorAccuracy : CIDetectorAccuracyHigh])
// 1.2.直接探测二维码特征
guard let features = detector?.features(in: imageCi) else {
return ([], image)
}
// 存储处理好的图片
var resultImage = image
// 存储扫描结果数组
var result = [String]()
for feature in features {
let qrFeature = feature as! CIQRCodeFeature
result.append(qrFeature.messageString ?? "")
if isDrawQRCodeFrame == true {
resultImage = drawFrame(image: resultImage, feature: qrFeature)
}
}
return (result, resultImage)
}