没有直接的方法将 Image 转换为 UIImage。相反,您应该将 Image 视为 View,并尝试将该 View 转换为 UIImage。
Image符合View,所以我们已经有了我们需要的View。现在我们只需要将 View 转换为 UIImage 即可。
我们需要两个组件来实现这一目标。第一个函数将我们的图像/视图更改为 UIView,第二个函数将我们创建的 UIView 更改为 UIImage。
为了更加方便,这两个函数都被声明为其适当类型的扩展。
extension View {
// This function changes our View to UIView, then calls another function
// to convert the newly-made UIView to a UIImage.
public func asUIImage() -> UIImage {
let controller = UIHostingController(rootView: self)
// Set the background to be transparent incase the image is a PNG, WebP or (Static) GIF
controller.view.backgroundColor = .clear
controller.view.frame = CGRect(x: 0, y: CGFloat(Int.max), width: 1, height: 1)
UIApplication.shared.windows.first!.rootViewController?.view.addSubview(controller.view)
let size = controller.sizeThatFits(in: UIScreen.main.bounds.size)
controller.view.bounds = CGRect(origin: .zero, size: size)
controller.view.sizeToFit()
// here is the call to the function that converts UIView to UIImage: `.asUIImage()`
let image = controller.view.asUIImage()
controller.view.removeFromSuperview()
return image
}
}
extension UIView {
// This is the function to convert UIView to UIImage
public func asUIImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}
}
如何使用?
let image: Image = Image("MyImageName") // Create an Image anyhow you want
let uiImage: UIImage = image.asUIImage() // Works Perfectly
Bonus
正如我所说,我们将图像视为视图。在这个过程中,我们没有使用Image的任何特定特征,唯一重要的是我们的Image是一个View(符合View协议)。
这意味着通过这个方法,你不仅可以将Image转换为UIImage,还可以将任何View转换为UIImage。
var myView: some View {
// create the view here
}
let uiImage = myView.asUIImage() // Works Perfectly