How do I render a SwiftUI View that is not at the root hierarchy as a UIImage?

后端 未结 2 832
无人及你
无人及你 2020-12-01 09:02

Suppose I have a simple SwiftUI View that is not the ContentView such as this:

struct Test: View {        
    var body: some View {
        VStack {
                


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 09:16

    Solution of Asperi works, but if you need image without white background you have to add this line:

    controller.view.backgroundColor = .clear
    

    And your View extension will be:

    extension View {
        func asImage() -> UIImage {
            let controller = UIHostingController(rootView: self)
            
            // locate far out of screen
            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()
            controller.view.backgroundColor = .clear
            let image = controller.view.asImage()
            controller.view.removeFromSuperview()
            return image
        }
    }
    

提交回复
热议问题