How to convert a image to UIImage

前端 未结 2 1482
别跟我提以往
别跟我提以往 2020-12-06 11:15

since the documentation on swiftUI isn\'t great yet I wanted to ask how I can convert an \"image\" to an \"UIImage\" or how to convert an \"image\" to pngData/jpgData

<
相关标签:
2条回答
  • 2020-12-06 11:23

    There is no direct way of converting an Image to UIImage. instead, you should treat the Image as a View, and try to convert that View to a UIImage. Image conforms to View, so we already have the View we need. now we just need to convert that View to a UIImage.

    We need 2 components to achieve this. First, a function to change our Image/View to a UIView, and second one, to change the UIView we created to UIImage.

    For more Convenience, both functions are declared as Extensions to their appropriate types.

    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)
            
            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: `.asImage()`
            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)
            }
        }
    }
    

    How To Use?

    let image: Image = Image("MyImageName") // Create an Image anyhow you want
    let uiImage: UIImage = image.asUIImage() // Works Perfectly
    

    Bonus

    As i said, we are treating the Image, as a View. In the process, we don't use any specific features of Image, the only thing that is important is that our Image is a View (conforms to View protocol). This means that with this method, you can not only convert an Image to a UIImage, but also you can convert any View to a UIImage.

    var myView: some View {
    // create the view here
    }
    let uiImage = myView.asUIImage() // Works Perfectly
    
    0 讨论(0)
  • 2020-12-06 11:43

    Such thing is not possible with SwiftUI, and I bet it will never be. It goes againts the whole framework concept. However, you can do:

    let uiImage = UIImage(systemName: "circle.fill")
    
    let image = Image(uiImage: uiImage)
    
    0 讨论(0)
提交回复
热议问题