Skip to content

Instantly share code, notes, and snippets.

@akhtarraza
Created August 21, 2019 10:44
Show Gist options
  • Save akhtarraza/a57579f82a94f1bdf47e250ce50fa455 to your computer and use it in GitHub Desktop.
Save akhtarraza/a57579f82a94f1bdf47e250ce50fa455 to your computer and use it in GitHub Desktop.
Generate QRCode Image for a given string.
import UIKit
extension String {
func qrCode() -> UIImage? {
let data = self.data(using: .isoLatin1)
guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else {
return nil
}
qrFilter.setValue("M", forKey: "inputCorrectionLevel")
qrFilter.setValue(data, forKey: "inputMessage")
let scale: CGFloat = 100
// Render the image into a CoreGraphics image
guard let output = qrFilter.outputImage else {
return nil
}
let ciContext = CIContext()
guard let cgImage = ciContext.createCGImage(output, from: output.extent) else {
return nil
}
//Scale the image usign CoreGraphics
UIGraphicsBeginImageContext(CGSize(width: output.extent.size.width * scale, height: output.extent.size.width * scale))
guard let graphicsContext = UIGraphicsGetCurrentContext() else {
return nil
}
graphicsContext.interpolationQuality = CGInterpolationQuality.none
graphicsContext.draw(cgImage, in: graphicsContext.boundingBoxOfClipPath)
guard let previewImage = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
//Cleaning up .
UIGraphicsEndImageContext()
// Rotate the image
guard let qrCgImage = previewImage.cgImage else {
return nil
}
return UIImage(cgImage: qrCgImage, scale: previewImage.scale, orientation: .downMirrored)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment