Skip to content

Instantly share code, notes, and snippets.

@Lweek
Created August 1, 2015 08:35
Show Gist options
  • Save Lweek/c329322b759cdac3b7a6 to your computer and use it in GitHub Desktop.
Save Lweek/c329322b759cdac3b7a6 to your computer and use it in GitHub Desktop.
Generate QR code
//
// UIImage-QRCodeGenerator.swift
//
// Created by Vladimír Bělohradský on 09/07/15.
//
import QuartzCore
import UIKit
extension UIImage {
/**
Generate QR code image of given size and colors
- complexity: O(1)
- precondition: None
- requires: `QuartzCore`, `UIKit`
- parameter text: `String` to be encoded into code
- parameter size: `CGFloat` square side size
- parameter color: `UIColor` as QR code marks color
- parameter backgroundColor: `UIColor` as background color
- author: Vladimir Belohradsky
- date: 9.7.2015
- version: 1.0
- requires: iOS7+, Swift 2.0
- returns: `UIImage?` QR code
*/
@available(iOS 7.0, *)
class func qrCode(text: String, size: CGFloat, color: UIColor, backgroundColor: UIColor) -> UIImage? {
var qrImage: UIImage?
if let qrGenerator = CIFilter(name: "CIQRCodeGenerator"), let colorizer = CIFilter(name: "CIFalseColor") {
// convert text into more common encoding
let data = text.dataUsingEncoding(NSISOLatin1StringEncoding)
// filter that generate QR code
qrGenerator.setDefaults()
qrGenerator.setValue(data, forKey: "inputMessage")
qrGenerator.setValue("M", forKey: "inputCorrectionLevel")
// UIColor have to be converted to CGColor because colorspace issue
let colorCG = color.CGColor
let backgroundColorCG = backgroundColor.CGColor
// Color code and background
colorizer.setDefaults()
colorizer.setValue(qrGenerator.outputImage, forKey: "inputImage")
colorizer.setValue(CIColor(CGColor: colorCG), forKey: "inputColor0")
colorizer.setValue(CIColor(CGColor: backgroundColorCG), forKey: "inputColor1")
// draw small copy of code
let frame = colorizer.outputImage.extent
let cgImage = CIContext(options: nil).createCGImage(colorizer.outputImage, fromRect: frame) as CGImageRef
// resize image without AA
UIGraphicsBeginImageContext(CGSizeMake(size, size))
let context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, CGInterpolationQuality.None)
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// flip image
UIGraphicsBeginImageContext(finalImage.size)
CGContextDrawImage(UIGraphicsGetCurrentContext(),CGRectMake(0,0, size, size),finalImage.CGImage);
qrImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
return qrImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment