我是一名新的 iOS 开发人员。我想知道如何在 Swift 中生成条形码。
我已经有了代码,有多种资源可以学习如何读取条形码,但我没有找到任何关于从字符串生成条形码的资源。
非常感谢!
附注我知道有一个类似的问题,但它是针对 Objective-C 的。我不了解 Obj-C,而且我发现来自 .NET 很难。
最佳答案
您可以使用 CoreImage(导入 CoreImage
)过滤器来做到这一点!
class Barcode {
class func fromString(string : String) -> UIImage? {
let data = string.data(using: .ascii)
if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
if let outputCIImage = filter.outputImage {
return UIImage(ciImage: outputCIImage)
}
}
return nil
}
}
let img = Barcode.fromString("whateva")
较新的版本,带有guard
和可失败的初始化程序:
extension UIImage {
convenience init?(barcode: String) {
let data = barcode.data(using: .ascii)
guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else {
return nil
}
filter.setValue(data, forKey: "inputMessage")
guard let ciImage = filter.outputImage else {
return nil
}
self.init(ciImage: ciImage)
}
}
用法:
let barcode = UIImage(barcode: "some text") // yields UIImage?
根据docs :
Generates an output image representing the input data according to the ISO/IEC 15417:2007 standard. The width of each module (vertical line) of the barcode in the output image is one pixel. The height of the barcode is 32 pixels. To create a barcode from a string or URL, convert it to an NSData object using the NSASCIIStringEncoding string encoding.
关于ios - 如何在 Swift 中从字符串生成条形码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43937780/