GitHub
https://github.com/targetcloud/QRTool
先欢迎STAR!
如果读者对前面三篇掌握和使用有困难的话,那么可以直接把本博文的工具类拖到项目中,调用即可,如果读者有兴趣的话,也可以对前面三篇与工具类的代码作对比,可以发现许多代码全部都在工具类中,对外只公开了四个方法,其中两个是类方法,另外两个是对象方法,四个方法分别是
func scanQRCode(_ inView: UIView, isDrawFrame: Bool = true,drawStrokeColor:UIColor = UIColor.red,drawLindWidth:CGFloat = 5, resultBlock: @escaping(_ resultStrs:[String])->())
func setRectInterest(_ orignRect: CGRect)
class func detectorQRCodeImage(_ image: UIImage, isDrawQRCodeFrame: Bool = true,drawLineWidth:CGFloat = 5) -> (resultStrs: [String]?, resultImage: UIImage)
class func generatorQRCode(_ inputStr: String, centerImage: UIImage?,scaleXY: CGFloat = 20,drawSize:CGSize = CGSize(width: 80, height: 80)) -> UIImage
QRTool.shareInstance.setRectInterest(scanBackView.frame)
QRTool.shareInstance.scanQRCode(view) { (resultStrs) in
print(resultStrs)
}
我们先来看一下,封装成工具类之后,对前面三篇博文的调用变成下面这样
一、生成二维码
//
// ViewController.swift
// GeneratorQRCode
//
// Created by targetcloud on 2016/12/3.
// Copyright © 2016年 targetcloud. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var qrImg: UIImageView!
@IBOutlet weak var qrContent: UITextView!
@IBAction func generatorQRImg(_ sender: Any) {
view.endEditing(true)
let str = qrContent.text ?? ""
let resultImage = QRTool.generatorQRCode(str, centerImage: UIImage(named: "targetcloud.png"))
qrImg.image = resultImage
}
}
二、检测二维码
//
// ViewController.swift
// detectorQRCode
//
// Created by targetcloud on 2016/12/3.
// Copyright © 2016年 targetcloud. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var detectorImg: UIImageView!
@IBOutlet weak var resultTV: UITextView!
@IBAction func detect(_ sender: Any) {
guard let image = detectorImg.image else {return}
let result = QRTool.detectorQRCodeImage(image)
let strs = result.resultStrs
detectorImg.image = result.resultImage
for str in strs! {
resultTV.text.append(str+"\n")
}
let alertVC = UIAlertController(title: "结果", message: strs?.description, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "关闭", style: UIAlertActionStyle.default) { (action: UIAlertAction) in
self.dismiss(animated: true, completion: nil)
}
alertVC.addAction(action)
present(alertVC, animated: true, completi