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

How can I generate a barcode from a string in Swift?

我是一名新 iOS 开发人员。我想知道如何在 Swift.

中生成条形码

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

非常感谢!

P.S。我知道有一个类似的问题,但它是针对 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.

改进代码:

  • 条码缩放
  • 设置条码图片边距
  • 将 UIImage 转换为 NSData(由于某些原因,上面的代码无法实现)。
  • 条码图片分享不会失败(可能是同一个bug)

Swift 3

func generateBarcode(from string: String) -> UIImage? {

    let data = string.data(using: String.Encoding.ascii)

    if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
        filter.setDefaults()
        //Margin
        filter.setValue(7.00, forKey: "inputQuietSpace")
        filter.setValue(data, forKey: "inputMessage")
        //Scaling
        let transform = CGAffineTransform(scaleX: 3, y: 3)

        if let output = filter.outputImage?.applying(transform) {
            let context:CIContext = CIContext.init(options: nil)
            let cgImage:CGImage = context.createCGImage(output, from: output.extent)!
            let rawImage:UIImage = UIImage.init(cgImage: cgImage)

            //Refinement code to allow conversion to NSData or share UIImage. Code here:
            //
            let cgimage: CGImage = (rawImage.cgImage)!
            let cropZone = CGRect(x: 0, y: 0, width: Int(rawImage.size.width), height: Int(rawImage.size.height))
            let cWidth: size_t  = size_t(cropZone.size.width)
            let cHeight: size_t  = size_t(cropZone.size.height)
            let bitsPerComponent: size_t = cgimage.bitsPerComponent
            //THE OPERATIONS ORDER COULD BE FLIPPED, ALTHOUGH, IT DOESN'T AFFECT THE RESULT
            let bytesPerRow = (cgimage.bytesPerRow) / (cgimage.width  * cWidth)

            let context2: CGContext = CGContext(data: nil, width: cWidth, height: cHeight, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: cgimage.bitmapInfo.rawValue)!

            context2.draw(cgimage, in: cropZone)

            let result: CGImage  = context2.makeImage()!
            let finalImage = UIImage(cgImage: result)

            return finalImage

        }
    }

    return nil
}

如果你的部署目标至少是iOS8,你可以使用Core Image。这是我的 BarcodeGenerator class(你需要 import CoreImage):

class BarcodeGenerator {
    enum Descriptor: String {
        case code128 = "CICode128BarcodeGenerator"
        case pdf417 = "CIPDF417BarcodeGenerator"
        case aztec = "CIAztecCodeGenerator"
        case qr = "CIQRCodeGenerator"
    }

    class func generate(from string: String, 
                         descriptor: Descriptor, 
                               size: CGSize) -> CIImage? {
        let filterName = descriptor.rawValue

        guard let data = string.data(using: .ascii),
            let filter = CIFilter(name: filterName) else {
                return nil
        }

        filter.setValue(data, forKey: "inputMessage")

        guard let image = filter.outputImage else {
            return nil
        }

        let imageSize = image.extent.size

        let transform = CGAffineTransform(scaleX: size.width / imageSize.width,
                                               y: size.height / imageSize.height)
        let scaledImage = image.transformed(by: transform)

        return scaledImage
    }
}

可以这样用

BarcodeGenerator.generate(from: "barcode-string", 
                     descriptor: .code128, 
                          size: CGSize(width: 800, height: 300))

这样使用,

func createBarcodeFromString(barcode:String)->UIImage?{

    let data = self.data(using: .isoLatin1)
    guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else {
        return nil
    }
    filter.setValue(data, forKey: "inputMessage")
    filter.setValue(7.0, forKey:"inputQuietSpace")
    guard var ciImage = filter.outputImage else {
        return nil
    }

    let imageSize = ciImage.extent.integral
    let outputSize = CGSize(width:320, height: 60)
    ciImage = ciImage.transformed(by:CGAffineTransform(scaleX: outputSize.width/imageSize.width, y: outputSize.height/imageSize.height))

    let image = convertCIImageToUIImage(ciimage: ciImage)
    return image
}

func convertCIImageToUIImage(ciimage:CIImage)->UIImage{
    let context:CIContext = CIContext.init(options: nil)
    let cgImage:CGImage = context.createCGImage(ciimage, from: ciimage.extent)!
    let image:UIImage = UIImage.init(cgImage: cgImage)
    return image
}