override func viewDidLoad() { super.viewDidLoad() // 堆代码 duidaima.com let url = "https://apple.com" let qrImage = createQRCodeImage(content: url) let imageView = UIImageView(image: qrImage) view.addSubview(imageView) imageView.sizeToFit() imageView.center = view.center } func createQRCodeImage(content: String) -> UIImage? { guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil } let data = content.data(using: .utf8) filter.setValue(data, forKey: "inputMessage") guard let ciImage = filter.outputImage else { return nil } return UIImage(ciImage: ciImage) }createQRCodeImage 方法的作用是将传入的字符串内容转化为一个二维码图片:
5.最后将 CIImage 对象转成 UIImage 并返回
imageView.frame.size = CGSize(width: 200, height: 200)再次运行程序,发现尺寸是变大了,但很模糊,虽然用手机能够成功识别了,但明显不符合预期,其实正确调整二维码尺寸的方法是通过修改输出时的尺寸,CIImage 有个 transformed 的方法可以用来转换这个图片:
/* Returns a new image representing the original image with the transform * 'matrix' appended to it. */ open func transformed(by matrix: CGAffineTransform) -> CIImage 我们再修改一下 createQRCodeImage 方法,让原来的图片放大一些: func createQRCodeImage(content: String) -> UIImage? { guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil } let data = content.data(using: .utf8) filter.setValue(data, forKey: "inputMessage") let transform = CGAffineTransform(scaleX: 10, y: 10) guard let ciImage = filter.outputImage?.transformed(by: transform) else { return nil } return UIImage(ciImage: ciImage) }
再次运行程序,这次就显示完美了: