Skip to content

Instantly share code, notes, and snippets.

@affix
Created October 16, 2016 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save affix/4d2cce29a361637b814cd3664301d26b to your computer and use it in GitHub Desktop.
Save affix/4d2cce29a361637b814cd3664301d26b to your computer and use it in GitHub Desktop.
View Controller to Generate a QR Code with swift on macOS. Requires a NSImageView, NSTextField and NSButton
//
// ViewController.swift
// QRGen
//
// Created by Keiran Smith on 01/10/2016.
// Copyright © 2016 Keiran Smith. All rights reserved.
//
import Cocoa
import CoreImage
class ViewController: NSViewController {
var qrcodeImage: CIImage!
@IBOutlet weak var imgCode: NSImageView!
@IBOutlet weak var txtEncode: NSTextField!
@IBAction func btnGenerate(_ sender: NSButton) {
if txtEncode.stringValue == "" {
return
}
let data = txtEncode.stringValue.data(using: String.Encoding.isoLatin1, allowLossyConversion: false)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue("Q", forKey: "inputCorrectionLevel")
qrcodeImage = filter?.outputImage
/*
Convert the Image
*/
let size = NSSize(width: 219, height: 219)
let outputImage = filter?.value(forKey: kCIOutputImageKey) as! CIImage
let scaleX = imgCode.frame.size.width / qrcodeImage.extent.size.width
let scaleY = imgCode.frame.size.height / qrcodeImage.extent.size.height
qrcodeImage.applying(CGAffineTransform(scaleX: scaleX, y: scaleY))
let outputImageRect = NSRectFromCGRect(qrcodeImage.extent)
let qrImage = NSImage(size: size)
qrImage.lockFocus()
outputImage.draw(at: NSZeroPoint, from: outputImageRect, operation: NSCompositingOperation.sourceOver, fraction: 1.0)
qrImage.unlockFocus()
qrImage.size = size
print("Displaying QR Code")
imgCode.image = qrImage
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
@frcocoatst
Copy link

tried to convert it to Swift3, but

qrcodeImage.applying(CGAffineTransform(scaleX: scaleX, y: scaleY))

seems not to work properly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment