我正在尝试使用UIImage初始化程序将Image转换为SwiftUI init(uiImage:)。我的UIImage本身是由CIQRCodeGenerator CIFilter生成的CIImage创建的。我正在Xcode 11.1 GM种子1中的Playground上运行代码。这是我的全部代码:
import SwiftUI
import UIKit
func qrCodeImage(for string: String) -> Image? {
let data = string.data(using: String.Encoding.utf8)
guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
qrFilter.setValue(data, forKey: "inputMessage")
guard let ciImage = qrFilter.outputImage else { return nil }
let uiImage = UIImage(ciImage: ciImage)
let image = Image(uiImage: uiImage)
return image
}
let image = qrCodeImage(for: "fdsa")
结果如下:
即使我用CGAffineTransform(scaleX: 10, y: 10)
转换图像,最后生成的SwiftUI图像仍然是相同大小,但为空白。
答案 0 :(得分:0)
可以使用从数据初始化的Image
来确认我在SwiftUI UIImage
中遇到相同的问题。可以在调试暂停时验证图像是否已加载,但是它不会显示在SwiftUI图像中。
此解决方案对我有用:显式指定图像渲染模式。就我而言,我添加了以下内容:.renderingMode(.original)
答案 1 :(得分:0)
以下Generating QR Code with SwiftUI shows empty picture
中提供的解决方案代码如下:
var ciContext = CIContext()
func qrCodeImage(for string: String) -> Image? {
let data = string.data(using: String.Encoding.utf8)
guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
qrFilter.setValue(data, forKey: "inputMessage")
guard let ciImage = qrFilter.outputImage else { return nil }
let cgImage = ciContext.createCGImage(ciImage, from: ciImage.extent)
let uiImage = UIImage(cgImage: cgImage!)
let image = Image(uiImage: uiImage)
return image
}
let image = qrCodeImage(for: "fdsa")
结果: