如何更改QR码的颜色

时间:2017-02-16 17:57:33

标签: ios swift qr-code

我正在使用应该包含带有信息的QR码的应用程序,我知道如何做到这一点,但我必须将Qrcode的颜色从黑色设置为红色,我理解它应该很容易,但我找不到一个很好的答案让这成为可能,我会让我的代码和我的QrCode屏幕,谢谢。

import UIKit

class QRCodeViewController: UIViewController {
    @IBOutlet weak var imgQRCode: UIImageView!

    func generateQRCode(from string: String) -> UIImage? {
        let data = string.data(using: String.Encoding.utf8)
        if let filter = CIFilter(name: "CIQRCodeGenerator") {
            filter.setValue(data, forKey: "inputMessage")
            filter.setValue("H", forKey: "inputCorrectionLevel")

            guard let qrCodeImage = filter.outputImage
                else {
                    return nil
            }
            let scaleX = imgQRCode.frame.size.width / qrCodeImage.extent.size.width
            let scaleY = imgQRCode.frame.size.height / qrCodeImage.extent.size.height
            let transform = CGAffineTransform(scaleX: scaleX, y: scaleY)

                if let output = filter.outputImage?.applying(transform) {
                    return UIImage(ciImage: output)
                }
            }
            return nil
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let image = generateQRCode(from: "Este es el código generado")
        imgQRCode.image = image
    }
}

QRCODE

1 个答案:

答案 0 :(得分:14)

将您的代码更改为此类内容。

func generateQRCode(from string: String) -> UIImage? {
    let data = string.data(using: String.Encoding.utf8)
    if let filter = CIFilter(name: "CIQRCodeGenerator") {
        guard let colorFilter = CIFilter(name: "CIFalseColor") else { return nil }

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

        filter.setValue("H", forKey: "inputCorrectionLevel")
        colorFilter.setValue(filter.outputImage, forKey: "inputImage")
        colorFilter.setValue(CIColor(red: 1, green: 1, blue: 1), forKey: "inputColor1") // Background white
        colorFilter.setValue(CIColor(red: 1, green: 0, blue: 0), forKey: "inputColor0") // Foreground or the barcode RED
        guard let qrCodeImage = colorFilter.outputImage
            else {
                return nil
        }
        let scaleX = imgQRCode.frame.size.width / qrCodeImage.extent.size.width
        let scaleY = imgQRCode.frame.size.height / qrCodeImage.extent.size.height
        let transform = CGAffineTransform(scaleX: scaleX, y: scaleY)


        if let output = colorFilter.outputImage?.applying(transform) {
            return UIImage(ciImage: output)
        }
    }
    return nil
}

更新需要Swift 3/4

if let output = colorFilter.outputImage?.transformed(by: transform) {
            return UIImage(ciImage: output)
        }

enter image description here