开发环境:Swift2.3 XCode8.0
本来是借鉴了别人的代码,时间太久了,无法找到原文。记录下来,以后用起来方便
func createQRForString(qrString:String, qrImageNamed:String? = nil) -> UIImage {
// 将字符串转换为二进制
let data = qrString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let filter = CIFilter(name: "CIQRCodeGenerator")!
filter.setValue(data, forKey: "inputMessage")
filter.setValue("H", forKey: "inputCorrectionLevel")
let qrCIImage = filter.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")
let codeImage = UIImage(CIImage: colorFilter.outputImage!.imageByApplyingTransform(CGAffineTransformMakeScale(5, 5)))
//内嵌logo
if qrImageNamed != nil {
if let iconImage = UIImage(named: qrImageNamed!) {
let rect = CGRectMake(0, 0, codeImage.size.width, codeImage.size.height)
UIGraphicsBeginImageContext(rect.size)
codeImage.drawInRect(rect)
let avatarSize = CGSizeMake(rect.size.width / 4, rect.size.height / 4)
let x = (rect.width - avatarSize.width) / 2
let y = (rect.height - avatarSize.height) / 2
iconImage.drawInRect(CGRectMake(x, y, avatarSize.width, avatarSize.height))
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage!
}
}
return codeImage
}
备注:LOGO的尺寸可以适当的放大些,使用了
filter.setValue("H", forKey: "inputCorrectionLevel")
后,二维码图片本身会变的很大。