-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathQRCode.swift
More file actions
103 lines (80 loc) · 2.79 KB
/
QRCode.swift
File metadata and controls
103 lines (80 loc) · 2.79 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// QRCode.swift
// QRCode
//
// Created by Alexander Schuch on 25/01/15.
// Copyright (c) 2015 Alexander Schuch. All rights reserved.
//
import UIKit
public typealias 🔳 = QRCode
/// QRCode generator
public struct QRCode {
/**
The level of error correction.
- Low: 7%
- Medium: 15%
- Quartile: 25%
- High: 30%
*/
public enum ErrorCorrection: String {
case Low = "L"
case Medium = "M"
case Quartile = "Q"
case High = "H"
}
/// Data contained in the generated QRCode
public let data: NSData
/// Foreground color of the output
/// Defaults to black
public var color = CIColor(red: 0, green: 0, blue: 0)
/// Background color of the output
/// Defaults to white
public var backgroundColor = CIColor(red: 1, green: 1, blue: 1)
/// Size of the output
public var size = CGSize(width: 200, height: 200)
/// The error correction. The default value is `.Low`.
public var errorCorrection = ErrorCorrection.Low
// MARK: Init
public init(_ data: NSData) {
self.data = data
}
public init?(_ string: String) {
if let data = string.dataUsingEncoding(NSISOLatin1StringEncoding) {
self.data = data
} else {
return nil
}
}
public init?(_ url: NSURL) {
if let data = url.absoluteString.dataUsingEncoding(NSISOLatin1StringEncoding) {
self.data = data
} else {
return nil
}
}
// MARK: Generate QRCode
/// The QRCode's UIImage representation
public var image: UIImage? {
guard let ciImage = ciImage else { return nil }
// Size
let ciImageSize = ciImage.extent.size
let widthRatio = size.width / ciImageSize.width
let heightRatio = size.height / ciImageSize.height
return ciImage.nonInterpolatedImage(withScale: Scale(dx: widthRatio, dy: heightRatio))
}
/// The QRCode's CIImage representation
public var ciImage: CIImage? {
// Generate QRCode
guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
qrFilter.setDefaults()
qrFilter.setValue(data, forKey: "inputMessage")
qrFilter.setValue(self.errorCorrection.rawValue, forKey: "inputCorrectionLevel")
// Color code and background
guard let colorFilter = CIFilter(name: "CIFalseColor") else { return nil }
colorFilter.setDefaults()
colorFilter.setValue(qrFilter.outputImage, forKey: "inputImage")
colorFilter.setValue(color, forKey: "inputColor0")
colorFilter.setValue(backgroundColor, forKey: "inputColor1")
return colorFilter.outputImage
}
}