Created
August 21, 2019 10:44
-
-
Save akhtarraza/a57579f82a94f1bdf47e250ce50fa455 to your computer and use it in GitHub Desktop.
Generate QRCode Image for a given string.
This file contains 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
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