文章来源:http://blog.csdn.net/sbt0198/article/details/54138425
func createQRForString(qrString:String, qrImageNamed:String? = nil) -> UIImage {
// 将字符串转换为二进制
let data = qrString.data(using: String.Encoding.utf8, 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!.transformed(by: CGAffineTransform(scaleX: 5, y: 5)))
//内嵌logo
if qrImageNamed != nil {
if let iconImage = UIImage(named: qrImageNamed!) {
let rect = CGRect(x:0, y:0, width:codeImage.size.width, height:codeImage.size.height)
UIGraphicsBeginImageContext(rect.size)
codeImage.draw(in: rect)
let avatarSize = CGSize(width:rect.size.width / 4, height:rect.size.height / 4)
let x = (rect.width - avatarSize.width) / 2
let y = (rect.height - avatarSize.height) / 2
iconImage.draw(in: CGRect(x:x, y:y, width:avatarSize.width, height:avatarSize.height))
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage!
}
}
return codeImage
}
网友评论