How do you change the Back and Foreground Color of a CIFilter CIQRCodeGenerator Filter

后端 未结 3 1443

I\'m trying to make a QR Code Generator for OS X but i haven\'t had succession in making a QRCode that can be more colourful that the black and white ones I\'m using the CIQRCod

3条回答
  •  情歌与酒
    2021-02-15 01:01

    Here's an example in swift (for the googlers)

    func qrCode(from string: String) -> UIImage? {
        let data = string.data(using: .ascii)
    
        // Generate the code image with CIFilter
        guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
        filter.setValue(data, forKey: "inputMessage")
    
        // Scale it up (because it is generated as a tiny image)
        let scale = UIScreen.main.scale
        let transform = CGAffineTransform(scaleX: scale, y: scale)
        guard let output = filter.outputImage?.transformed(by: transform) else { return nil }
    
        // Change the color using CIFilter
        let colorParameters = [
            "inputColor0": CIColor(color: UIColor.black), // Foreground
            "inputColor1": CIColor(color: UIColor.clear) // Background
        ]
        let colored = output.applyingFilter("CIFalseColor", parameters: colorParameters)
    
        return UIImage(ciImage: colored)
    }
    

提交回复
热议问题