imageView.image = UIImage(ciImage: ) 不会第二次更新



案例:我看到了一个UISwitch按钮。当开关关闭时,imageView将显示由字符串生成的QRCode图像。启用时,它将显示由字符串生成的条形码图像。我从中复制了QRCode和条形码生成功能https://www.hackingwithswift.com/并且它们运行良好

问题是imageView仅第一次显示生成的图像。在QRCode和条形码之间切换时,imageView将不再更新。我100%确信UISwitch正在工作,函数被调用并返回生成的图像。我已经用断点和打印进行了多次测试,函数不会返回零或空图像。

这是QRCode生成代码

func generateQRCode(from string: String) -> UIImage? {
let data = string.data(using: String.Encoding.ascii)
if let filter = CIFilter(name: "CIQRCodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 3, y: 3)
if let output = filter.outputImage?.transformed(by: transform) {
return UIImage(ciImage: output) //<== it always returns this
}
}
return nil
}

这是条形码生成代码

func generateBarcode(from string: String) -> UIImage? {
let data = string.data(using: String.Encoding.ascii)
if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 3, y: 3)
if let output = filter.outputImage?.transformed(by: transform) {
return UIImage(ciImage: output) //<== it always returns this
}
}
return nil
}

以下是我如何在QRCode和条形码之间切换并且逻辑是正确的

func toggleBarcode(isBarcode : Bool) {
if isBarcode {
qrImageView.image = generateBarcode(from: "Hacking with Swift")
} else {
qrImageView.image = generateQRCode(from: "Hacking with Swift")
}
}

当使用之类的东西进行测试时

qrImageView.image = UIImage(named: "myimage")

它每次都有效。

imageView不会只更新UIImage(ciImage:(

我甚至用几个不同版本的QR和条形码生成代码进行了测试,它们都不会第二次更新imageView。

我试过

qrImageView.setNeedsDisplay()

但没有运气。

快速搜索。。。似乎是一个";bug";或者改变。。。

将生成器代码更改为这样似乎可以纠正问题:

func generateQRCode(from string: String) -> UIImage? {
let data = string.data(using: String.Encoding.ascii)
let context = CIContext()
if let filter = CIFilter(name: "CIQRCodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 3, y: 3)

if let output = filter.outputImage?.transformed(by: transform) {
if let retImg = context.createCGImage(output, from: output.extent) {
return UIImage(cgImage: retImg)
}
}
}
return nil
}
func generateBarcode(from string: String) -> UIImage? {
let data = string.data(using: String.Encoding.ascii)
let context = CIContext()
if let filter = CIFilter(name: "CICode128BarcodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 3, y: 3)

if let output = filter.outputImage?.transformed(by: transform) {
if let retImg = context.createCGImage(output, from: output.extent) {
return UIImage(cgImage: retImg)
}
}
}
return nil
}

相关内容

  • 没有找到相关文章

最新更新