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

标签 ios swift barcode core-image

我是一名新的 iOS 开发者。我想知道如何在 Swift 中生成条形码。

我已经有了代码,有多种资源可以学习如何读取条形码,但我没有找到任何关于从字符串生成条形码的内容。

非常感谢!

附言我知道有一个类似的问题,但它是针对 Objective-C 的。我不了解 Obj-C,我发现从 .NET 过来很难。

最佳答案

您可以使用 CoreImage(import 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/28542240/

相关文章:

ios - 在 Swift 中加速 TableView 加载 JSON

printing - 从网页将条形码打印到Zebra打印机

.net - 如何调整条码大小

barcode - 使用条码扫描器作为键盘楔子是否意味着您无法确认收到扫描件?

ios - 当键盘出现 Swift 时,使用文本字段和按钮向上移动 View

ios - FFmpeg 将流保存到 mp3

ios - 更新 CoreData 中的项目不会刷新 tableView

ios - 如何在导航栏右侧添加多个 UIBarButtonItems?

ios - 一起点击或按下时在两个 UIlabel 之间画一条线

ios - 在 Swift 中扩展 UIGestureRecognizer