网上的各种生成二维码图片的代码,我综合了一下,觉得自己的这个较好一些。直接上代码。
<pre>//生成二维码图片
func generateQRCodeImage(_ content: String, size: CGSize) -> UIImage?
{
// 创建滤镜
guard let filter = CIFilter(name: "CIQRCodeGenerator") else {return nil}
// 还原滤镜的默认属性
filter.setDefaults()
// 设置需要生成的二维码数据
let contentData = content.data(using: String.Encoding.utf8)
filter.setValue(contentData, forKey: "inputMessage")
// 从滤镜中取出生成的图片
guard let ciImage = filter.outputImage else {return nil}
let context = CIContext(options: nil)
let bitmapImage = context.createCGImage(ciImage, from: ciImage.extent)
let colorSpace = CGColorSpaceCreateDeviceGray()
let bitmapContext = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.none.rawValue)
//draw image
let scale = min(size.width / ciImage.extent.width, size.height / ciImage.extent.height)
bitmapContext!.interpolationQuality = CGInterpolationQuality.none
bitmapContext?.scaleBy(x: scale, y: scale)
bitmapContext?.draw(bitmapImage!, in: ciImage.extent)
//保存bitmap到图片
guard let scaledImage = bitmapContext?.makeImage() else {return nil}
return UIImage(cgImage: scaledImage)
}
</pre>
传入一个需要生成二维码的字符串和CGsize就会返回一张二维码图片。