gpt4 book ai didi

uikit - 从 UIImage 转换为 SwiftUI Image 会产生相同大小的空白图像

转载 作者:行者123 更新时间:2023-12-01 11:12:35 29 4
gpt4 key购买 nike

我正在尝试转换 UIImage到 SwiftUI Image使用 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")

结果如下:

enter image description here

即使我用 CGAffineTransform(scaleX: 10, y: 10) 转换图像,最后生成的 SwiftUI Image 仍然是相同的大小,但是是空白的。

最佳答案

以下解决方案提供于: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")

结果:

screenshot in swift playground

关于uikit - 从 UIImage 转换为 SwiftUI Image 会产生相同大小的空白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58087991/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com