swift生成具有透明背景的qr代码

时间:2016-03-04 07:07:05

标签: ios swift

在我的swift 2应用程序中,我可以生成如下的QR码:

let data = "1234567890".dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter!.setValue(data, forKey: "inputMessage")
filter!.setValue("Q", forKey: "inputCorrectionLevel")
qrcodeImage = filter!.outputImage
let transformedImage = qrcodeImage.imageByApplyingTransform(CGAffineTransformMakeScale(150, 150))
QRCodeImage.image = UIImage(CIImage: transformedImage)

但是我的QR码获得了白色背景图片,但我希望有一个透明的背景。

我试过这样的事情:

QRCodeImage.backgroundColor = UIColor.clearColor()

但这不起作用。 任何的想法 ? :)

8 个答案:

答案 0 :(得分:6)

CIQRCodeGenerator过滤器似乎总是使用黑白。

您可以将输出传递到CIMaskToAlpha过滤器,将其转换为透明:

首先,您可能希望使用CIColorInvert来交换白色&黑色。

答案 1 :(得分:1)

对于透明背景,你应该(用你的直觉和)尝试这样,

//Create a CIFalseColor Filter
let colorFilter: CIFilter = CIFilter(name: "CIFalseColor")!

colorFilter.setDefaults()

colorFilter.setValue(yourQRFilter.outputImage!, forKey: "inputImage")

//Then set the background colour like this,
let transparentBG: CIColor = CIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)

colorFilter.setValue(qrColor, forKey: "inputColor0")

colorFilter.setValue(transparentBG, forKey: "inputColor1")

outputImage = colorFilter.outputImage!

我希望这会产生具有透明背景的QRCode图像。

答案 2 :(得分:0)

我认为关键将在背景的alpha上。您可以设置或减少Alpha,减少或删除透明度。尝试这样的事情:

QRCodeImage.backgroundcolor = UIColor(white: 1, alpha: 0.5)

希望它有所帮助。

答案 3 :(得分:0)

这是我的代码:

func QRImageFromData(_ data: Data) -> UIImage? {

    let filter = CIFilter(name: "CIQRCodeGenerator")
    filter?.setValue(data, forKey: "inputMessage")
    //filter?.setValue("H", forKey: "inputCorrectionLevel")

    //change qrcode color : #1e3259
    let filterFalseColor = CIFilter(name: "CIFalseColor")
    filterFalseColor?.setDefaults()
    filterFalseColor?.setValue(filter?.outputImage, forKey: "inputImage")
    // convert method
    let cgColor: CGColor? = UIColor(hex: "#1e3259")?.cgColor
    let qrColor: CIColor = CIColor(cgColor: cgColor!)
    let transparentBG: CIColor = CIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
    filterFalseColor?.setValue(qrColor, forKey: "inputColor0")
    filterFalseColor?.setValue(transparentBG, forKey: "inputColor1")


    if let image = filterFalseColor?.outputImage {
        let transform = CGAffineTransform(scaleX: 5.0, y: 5.0)
        return UIImage(ciImage: image.applying(transform),
            scale: 1.0,
            orientation: UIImageOrientation.up)
    } else {
        return nil
    }

}

答案 4 :(得分:0)

tutorial之后,我获得了具有透明背景的qr。

添加以下扩展名:

extension CIImage {
    /// Inverts the colors and creates a transparent image by converting the mask to alpha.
    /// Input image should be black and white.
    var transparent: CIImage? {
        return inverted?.blackTransparent
    }

    /// Inverts the colors.
    var inverted: CIImage? {
        guard let invertedColorFilter = CIFilter(name: "CIColorInvert") else { return nil }

        invertedColorFilter.setValue(self, forKey: "inputImage")
        return invertedColorFilter.outputImage
    }

    /// Converts all black to transparent.
    var blackTransparent: CIImage? {
        guard let blackTransparentFilter = CIFilter(name: "CIMaskToAlpha") else { return nil }
        blackTransparentFilter.setValue(self, forKey: "inputImage")
        return blackTransparentFilter.outputImage
    }

    /// Applies the given color as a tint color.
    func tinted(using color: UIColor) -> CIImage?
    {
        guard
            let transparentQRImage = transparent,
            let filter = CIFilter(name: "CIMultiplyCompositing"),
            let colorFilter = CIFilter(name: "CIConstantColorGenerator") else { return nil }

        let ciColor = CIColor(color: color)
        colorFilter.setValue(ciColor, forKey: kCIInputColorKey)
        let colorImage = colorFilter.outputImage

        filter.setValue(colorImage, forKey: kCIInputImageKey)
        filter.setValue(transparentQRImage, forKey: kCIInputBackgroundImageKey)

        return filter.outputImage!
    }
}


extension URL {

    func qrImage(using color: UIColor) -> UIImage? {
        let ciImage = qrCIImage?.tinted(using: color)
        return ciImage != nil ? UIImage(ciImage: ciImage!) : nil
    }

    var qrImage: UIImage? {
        return UIImage(ciImage: qrCIImage!)
    }

    /// Creates a QR code for the current URL in the given color.
    func qrCIImage(using color: UIColor) -> CIImage? {
        return qrCIImage?.tinted(using: color)
    }

    /// Returns a black and white QR code for this URL.
    var qrCIImage: CIImage? {
        guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
        let qrData = absoluteString.data(using: String.Encoding.ascii)
        qrFilter.setValue(qrData, forKey: "inputMessage")

        let qrTransform = CGAffineTransform(scaleX: 12, y: 12)
        return qrFilter.outputImage?.transformed(by: qrTransform)
    }

}

然后像这样使用:

let myChosenColor = UIColor(red:0.93, green:0.31, blue:0.23, alpha:1.00)
let qrURLImage = URL(string: "https://stackoverflow.com")?.qrImage(using: myChosenColor)
myQrImageView.image = qrURLImage

在myQrImageView.image内,您将看到具有透明背景的qr图像:

答案 5 :(得分:0)

除了回答@jtbandes之外,我还写了一些代码,因此对其他人也有帮助

extension UIImage {

    func transparentBackground() -> UIImage? {
        let context = CIContext(options: nil)
        let filter = CIFilter(name: "CIMaskToAlpha")
        filter?.setDefaults()
        filter?.setValue(self.ciImage, forKey: kCIInputImageKey)
        if let output = filter?.outputImage,
           let imageRef = context.createCGImage(output, from: output.extent) {
            return UIImage(cgImage: imageRef)
        }
        return nil
    }

    func invertColor() -> UIImage? {
        let filter = CIFilter(name: "CIColorInvert")
        filter?.setDefaults()
        filter?.setValue(self.ciImage, forKey: kCIInputImageKey)
        if let output = filter?.outputImage {
            return UIImage(ciImage: output)
        }
        return nil
    }

}

并像这样使用它

yourUIImage.invertColor()?.transparentBackground()

transparentBackground()函数将删除黑色并保留白色,而invertColor()将黑色替换为白色

答案 6 :(得分:0)

extension UIImage {
    func alpha(_ value: CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(at: CGPoint.zero, blendMode: .normal, alpha: value)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

答案 7 :(得分:0)

您正在寻找的现成解决方案:

enum GeneratorType {
  case qrCode, barCode, aztecCode
  
  var filterName: String {
    switch self {
    case .aztecCode:
      return "CIAztecCodeGenerator"
    case .barCode:
      return "CICode128BarcodeGenerator"
    case .qrCode:
      return "CIQRCodeGenerator"
    }
  }
}

func generateCode(type: GeneratorType, text: String,
                  transform: CGAffineTransform = CGAffineTransform(scaleX: 32.0, y: 32.0),
                  fillColor: UIColor = UIColor.black,
                  backgroundColor: CIColor = CIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)) -> UIImage? {
  guard let filter = CIFilter(name: type.filterName) else {
    return nil
  }
  
  filter.setDefaults()
  
  guard let data = text.data(using: String.Encoding.utf8) else {
    return nil
  }
  
  filter.setValue(data, forKey: "inputMessage")
  
  let filterFalseColor = CIFilter(name: "CIFalseColor")
  filterFalseColor?.setDefaults()
  filterFalseColor?.setValue(filter.outputImage, forKey: "inputImage")
  filterFalseColor?.setValue(CIColor(cgColor: fillColor.cgColor), forKey: "inputColor0")
  filterFalseColor?.setValue(backgroundColor, forKey: "inputColor1")
  
  
  guard let image = filterFalseColor?.outputImage else { return nil }
  
  return UIImage(ciImage: image.transformed(by: transform), scale: 1.0,
                 orientation: UIImage.Orientation.up)
}

用法:

let qrImage = generateCode(type: .qrCode, text: "some text")

和平!