使用 SwiftUI 生成二维码显示空图片 [英] Generating QR Code with SwiftUI shows empty picture
问题描述
我正在尝试在我的应用中生成二维码.问题是每当我做图片时,图片只是一个空方块.我将代码简化为基础,以尝试展示我的问题.
im trying to generate a QR code in my app. The problem is that whenever I do the picture is just an empty square. I stripped down the code to the basics to try and show my problem.
struct ContentView: View {
@State var image: Image = Image(systemName: "circle.fill")
var body: some View {
VStack {
image
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 200, height: 200)
.background(Color.green)
}.onAppear {
let myString = "Hello There"
let data = myString.data(using: String.Encoding.ascii)
guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return }
qrFilter.setValue(data, forKey: "inputMessage")
guard let qrImage = qrFilter.outputImage else { return }
let transform = CGAffineTransform(scaleX: 10, y: 10)
let scaledQrImage = qrImage.transformed(by: transform)
self.image = Image(uiImage: UIImage(ciImage: scaledQrImage))
}
}
}
结果如下:
推荐答案
我想问题在于您的 CIImage
实际上并未生成".你看,CIImage
只是一个配方,用于需要由 CIContext
渲染成实际位图图像的图像.
I guess the problem is that your CIImage
is not actually "produced". You see, a CIImage
is just a recipe for an image that needs to be rendered by a CIContext
into an actual bitmap image.
(记录不足)方便的初始化程序 UIImage(ciImage:)
仅在您分配图像的目标理解 UIImage
的像素尚未there 并且需要首先渲染.UIImageView
可以处理这个问题,但 SwiftUI 的 Image
似乎不能.
The (poorly documented) convenient initializer UIImage(ciImage:)
only works if the destination you assign the image to understands that the pixels of the UIImage
are not yet there and need to be rendered first. UIImageView
could handle this, but it seems SwiftUI's Image
doesn't.
您需要做的是创建一个 CIContext
(一次,可能作为您的视图的一个属性)并使用它来将您的条形码图像渲染成这样的位图:
What you need to do is to create a CIContext
(once, maybe as a property of your view) and use it to render your barcode image into a bitmap like this:
let cgImage = self.ciContext.createCGImage(scaledQrImage, from: scaledQrImage.extent)
self.image = Image(uiImage: UIImage(cgImage: cgImage))
这篇关于使用 SwiftUI 生成二维码显示空图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!