条形码不生成

时间:2018-04-30 13:04:44

标签: ios swift uiimage barcode cifilter

我使用此link中的以下代码从字符串生成Code128条形码。出于某种原因,它并没有开玩笑。该功能会返回图像,但在将图像分配给UIImageView后,我无法在模拟器中看到它。

 class Barcode {

    class func fromString(string : String) -> UIImage? {

        let data = string.data(using: .ascii)
        let filter = CIFilter(name: "CICode128BarcodeGenerator")
        filter?.setValue(data, forKey: "inputMessage")

        return UIImage(ciImage: (filter?.outputImage)!)
    }

}

已导入CoreImage。函数调用:

let barcodeImg = Barcode.fromString(string: number)
self.userBarcodeImageView.image = barcodeImg

谁能告诉我这是什么问题?

解决

替换此功能的代码,可在此link

中找到
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:
        //http://stackoverflow.com/questions/2240395/uiimage-created-from-cgimageref-fails-with-uiimagepngrepresentation
        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
}

让它发挥作用。

1 个答案:

答案 0 :(得分:0)

我遇到过同样的问题。经过长时间的研究发现以下解决方案。

请确保您的imageView高度和宽度应为整数。如果imageView高度和宽度为浮点数,则它不会生成barcode图像。