Skip to content

Instantly share code, notes, and snippets.

@vijayparikh
Created March 15, 2018 06:53
Show Gist options
  • Save vijayparikh/057e12c05e24738777cec1fa93fdb825 to your computer and use it in GitHub Desktop.
Save vijayparikh/057e12c05e24738777cec1fa93fdb825 to your computer and use it in GitHub Desktop.
Generate a QRCode and scale it to a UIImageView working perfectly for AppleTV 4K, iPhone X and iPadPro using Xcode 9.2
@IBOutlet weak var qrCodeBox: UIImageView!
func createQRFromString(_ str: String, size: CGSize) -> UIImage {
let stringData = str.data(using: .utf8)
let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
qrFilter.setValue(stringData, forKey: "inputMessage")
qrFilter.setValue("H", forKey: "inputCorrectionLevel")
let minimalQRimage = qrFilter.outputImage!
// NOTE that a QR code is always square, so minimalQRimage..width === .height
let minimalSideLength = minimalQRimage.extent.width
let smallestOutputExtent = (size.width < size.height) ? size.width : size.height
let scaleFactor = smallestOutputExtent / minimalSideLength
let scaledImage = minimalQRimage.transformed(
by: CGAffineTransform(scaleX: scaleFactor, y: scaleFactor))
return UIImage(ciImage: scaledImage,
scale: UIScreen.main.scale,
orientation: .up)
}
override func viewDidLoad() {
super.viewDidLoad()
let myQRimage = createQRFromString("https://www.apple.com",
size: qrCodeBox.frame.size)
qrCodeBox.image = myQRimage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment