点击按钮生成图像



我想在swiftUI中点击按钮后加载qimage。现在我只是将函数生成的uiimage直接传递到图像帧中。如何在按钮操作部分中呈现功能?

现在我的代码是这样的;

struct QRCodeView: View {
@State private var UUID = "usufuf321"
@State private var phoneNo = "09-012948"
let context = CIContext()
let filter = CIFilter.qrCodeGenerator()
var body: some View {
GroupBox{
VStack(alignment: .center, spacing: 10){
Image(uiImage: QRGenerator(from: "(UUID)n(phoneNo)"))
.interpolation(.none)
.resizable()
.scaledToFit()
.frame(width: 250, height: 250, alignment: .center)
.clipped()

Button(action: {

}, label: {
Text ("GENERATE")
.scaledToFit()
.frame(width: 250, height: 60, alignment: .center)
.cornerRadius(12)
})

}
.frame(maxWidth:.infinity, alignment: .center)
}
.cornerRadius(20)
.padding(.all,10)
}
func QRGenerator(from string: String) -> UIImage {
let data = Data(string.utf8)
filter.setValue(data, forKey: "inputMessage")
if let outputImage = filter.outputImage {
if let cgimg = context.createCGImage(outputImage, from: outputImage.extent) {
return UIImage(cgImage: cgimg)
}
}
return UIImage(systemName: "xmark.circle") ?? UIImage()

}
}

使用@State

struct QRCodeView: View {

@State private var qrImage: Image?

var body: some View {
GroupBox{
VStack(alignment: .center, spacing: 10){
if let qrImage = qrImage {
qrImage
.interpolation(.none)
.resizable()
.scaledToFit()
.frame(width: 250, height: 250, alignment: .center)
.clipped()
}

Button(action: {
qrImage = Image(uiImage: QRGenerator(from: "(UUID)n(phoneNo)"))
}, label: {
Text ("GENERATE")
.scaledToFit()
.frame(width: 250, height: 60, alignment: .center)
.cornerRadius(12)
})

}
.frame(maxWidth:.infinity, alignment: .center)
}
}
}

最新更新