Created
May 17, 2019 04:13
-
-
Save yusuke024/f9ac55306cdd25d4c5e4d1f522ab31c8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import PlaygroundSupport | |
class QRCodeView: UIView { | |
lazy var filter = CIFilter(name: "CIQRCodeGenerator") | |
lazy var imageView = UIImageView() | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
addSubview(imageView) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
imageView.frame = bounds | |
} | |
func generateCode(_ string: String, foregroundColor: UIColor = .black, backgroundColor: UIColor = .white) { | |
guard let filter = filter, | |
let data = string.data(using: .isoLatin1, allowLossyConversion: false) else { | |
return | |
} | |
filter.setValue(data, forKey: "inputMessage") | |
guard let ciImage = filter.outputImage else { | |
return | |
} | |
let transformed = ciImage.transformed(by: CGAffineTransform.init(scaleX: 10, y: 10)) | |
let invertFilter = CIFilter(name: "CIColorInvert") | |
invertFilter?.setValue(transformed, forKey: kCIInputImageKey) | |
let alphaFilter = CIFilter(name: "CIMaskToAlpha") | |
alphaFilter?.setValue(invertFilter?.outputImage, forKey: kCIInputImageKey) | |
if let outputImage = alphaFilter?.outputImage { | |
imageView.tintColor = foregroundColor | |
imageView.backgroundColor = backgroundColor | |
imageView.image = UIImage(ciImage: outputImage, scale: 2.0, orientation: .up) | |
.withRenderingMode(.alwaysTemplate) | |
} | |
} | |
} | |
let frame = CGRect(origin: .zero, size: .init(width: 320, height: 320)) | |
let view = QRCodeView(frame: frame) | |
view.generateCode("https://google.com", | |
foregroundColor: UIColor(red:1.00, green:0.02, blue:0.35, alpha:1.00), | |
backgroundColor: UIColor(red:1.00, green:0.82, blue:0.86, alpha:1.00)) | |
PlaygroundPage.current.liveView = view | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment