QRCode不但可以使用在pc中的一些程序調用生成二維碼同時也支持在手機中直接調用開發,下面來看一個Swift使用CIFilter生成二維碼圖片的例子。
CIFilter提供了各種各樣的濾鏡,其中CIQRCodeGenerator可以用來生成二維碼。下面通過一個樣例演示如何將字符串(鏈接也是字符串)生成二維碼圖片,同時支持在二維碼中間放置個性化圖標。
效果圖如下:
代碼如下
復制代碼
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//不帶圖片的二維碼圖片
let imageViewIcon1 = UIImageView(frame: CGRectMake(20, 20, 150, 150))
imageViewIcon1.image = createQRForString("http://www.111cn.net",
qrImageName: "")
self.view.addSubview(imageViewIcon1)
//帶圖片的二維碼圖片
let imageViewIcon2 = UIImageView(frame: CGRectMake(200, 20, 150, 150))
imageViewIcon2.image = createQRForString("http://www.111cn.net",
qrImageName: "logo")
self.view.addSubview(imageViewIcon2)
}
//創建二維碼圖片
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
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}