How to generate QR code in AppKit

Issue #140

I need to generate QR code in https://github.com/onmyway133/AddressGenerator. Fortunately with CoreImage filter, it is very easy. Code is in Swift 4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import AppKit

final class QRCodeGenerator {
func generate(string: String, size: CGSize) -> NSImage? {
guard let data = string.data(using: .utf8) else {
return nil
}

// Filter
guard let filter = CIFilter(name: "CIQRCodeGenerator") else {
return nil
}

filter.setValue(data, forKey: "inputMessage")
filter.setValue("Q", forKey: "inputCorrectionLevel")

// CIImage
guard let ciImage = filter.outputImage else {
return nil
}

// NSImage
let rep = NSCIImageRep(ciImage: ciImage)
let image = NSImage(size: rep.size)
image.addRepresentation(rep)

// Scale
let finalImage = NSImage(size: size)
finalImage.lockFocus()
NSGraphicsContext.current?.imageInterpolation = .none
image.draw(in: NSRect(origin: .zero, size: size))
finalImage.unlockFocus()

return finalImage
}
}

Comments