Created
March 15, 2018 06:53
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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