Skip to content

Instantly share code, notes, and snippets.

@weverb2
Created October 12, 2016 12:33
Show Gist options
  • Save weverb2/a5ba1f111beb1d546753775461b2ea9f to your computer and use it in GitHub Desktop.
Save weverb2/a5ba1f111beb1d546753775461b2ea9f to your computer and use it in GitHub Desktop.
Generate Barcode from a string
import UIKit
class Barcode {
class func fromString(string : String, barcodeMode: BarcodeMode) -> UIImage? {
let data = string.dataUsingEncoding(NSASCIIStringEncoding)
let filter = CIFilter(name: barcodeMode.filterName)
filter?.setValue(data, forKey: "inputMessage")
guard let outputImage = filter?.outputImage else {
return UIImage()
}
let transform = CGAffineTransformMakeScale(5.0, 5.0)
let output = outputImage.imageByApplyingTransform(transform)
let context = CIContext(options: nil)
let newImage = UIImage (CGImage: context.createCGImage(output, fromRect: output.extent))
return newImage
}
}
enum BarcodeMode {
case Barcode
case QRCode
var filterName :String {
switch self{
case .Barcode:
return "CICode128BarcodeGenerator"
case .QRCode:
return "CIQRCodeGenerator"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment