美文网首页
swift 系统生成二维码

swift 系统生成二维码

作者: 紫荆逸 | 来源:发表于2017-12-13 14:47 被阅读6次

    文章来源: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
        }
    

    相关文章

      网友评论

          本文标题:swift 系统生成二维码

          本文链接:https://www.haomeiwen.com/subject/ywnaixtx.html