ios - 如何在 Swift 中从字符串生成条形码?

标签 ios swift barcode core-image

我是一名新的 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/

相关文章:

iOS 应用程序将保存密码但不会自动填充

arrays - 检查 swift 数组是否不包含对象

ios - 无法重新加载 TableView

ios - 如何让 UIImageView 填充 UITableViewCell?

ruby-on-rails - 如何从 Ruby on Rails 应用程序打印(条形码)标签?

ios - 收到推送通知后重定向到特定屏幕 - Swift

iOS Corebluetooth - 有时在我重置网络之前不会连接到设备

flutter - 如何在flutter中在PDF文件上生成QR码

ios - WKWebView不使用URLCache

c# - 如何在不使用 TextChanged 事件的情况下在 Winform 上捕获整个条码值?