//创建二维码图片
func createQRForString(qrString: String?, qrImage: UIImage?) -> UIImage?{
if let sureQRString = qrString {
let stringData = sureQRString.data(using: .utf8, 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!.applying(CGAffineTransform(scaleX: 5, y: 5)))
let codeImage = UIImage(ciImage: colorFilter.outputImage!.transformed(by: CGAffineTransform(scaleX: 5, y: 5)))
// 通常,二维码都是定制的,中间都会放想要表达意思的图片
if let iconImage = qrImage {
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 * 0.25, height:rect.size.height * 0.25)
let x = (rect.width - avatarSize.width) * 0.5
let y = (rect.height - avatarSize.height) * 0.5
iconImage.draw(in: CGRect(x:x, y:y, width:avatarSize.width, height:avatarSize.height))
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage
}
return codeImage
}
return nil
}
[Swift] 生成二维码
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Swift - 自动布局库SnapKit 来源:原文 为了适应各种屏幕尺寸,iOS 6后引入了自动布局(Auto ...