将 SwiftUI 视图渲染为 UIImage

Ant*_*ony 10 xcode render snapshot ios swiftui

我正在尝试将 SwiftUI 视图呈现为 UIImage,然后让用户选择保存到相机胶卷或通过电子邮件发送给其他人。

例如,我想将 50 行的列表呈现到 UIImage 中。

struct MyList: View {
    var body: some View {
        List {
            ForEach(0 ..< 50, id:\.self) {
                Text("row \($0)")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

过去几周在互联网上搜索仍然没有运气。我尝试了 2 种不同的方法。

1. UIHostingController来源在这里

let hosting = UIHostingController(rootView: Text("TEST"))
hosting.view.frame = // Calculate the content size here //
let snapshot = hosting.view.snapshot        // output: an empty snapshot of the size
print(hosting.view.subviews.count)          // output: 0
Run Code Online (Sandbox Code Playgroud)

我试过layoutSubviews(), setNeedsLayout(), layoutIfNeeded(), loadView(),但结果仍然是 0 个子视图。

2. UIWindow.rootViewController来源在这里

var vc = UIApplication.shared.windows[0].rootViewController
vc = vc.visibleController          // loop through the view controller stack to find the top most view controller
let snapshot = vc.view.snapshot    // output: a snapshot of the top most view controller
Run Code Online (Sandbox Code Playgroud)

这几乎产生了我想要的输出。然而,我得到的快照实际上是一个屏幕截图,即带有导航栏、标签栏和固定大小(与屏幕大小相同)。我需要捕获的只是没有这些条的视图内容,有时可能比屏幕大(我的视图在这个例子中是一个很长的列表)。

试图查询vc.view.subviews以查找我想要的表视图,但返回一个无用的[<_TtGC7SwiftUI16PlatformViewHostGVS_42PlatformViewControllerRepresentableAdaptorGVS_16BridgedSplitViewVVS_22_VariadicView_Children7ElementGVS_5GroupGVS_19_ConditionalContentS4_GVS_17_UnaryViewAdaptorVS_9EmptyView______: 0x7fb061cc4770; frame = (0 0; 414 842); anchorPoint = (0, 0); tintColor = UIExtendedSRGBColorSpace 0 0.478431 1 1; layer = <CALayer: 0x600002d8caa0>>].

任何帮助深表感谢。

fuz*_*uzz 6

Would something like this work for you?

import SwiftUI

extension UIView {
    func takeScreenshot() -> UIImage {
        // Begin context
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
        // Draw view in that context
        drawHierarchy(in: self.bounds, afterScreenUpdates: true)
        // And finally, get image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        if (image != nil) {
            UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil);
            return image!
        }

        return UIImage()
    }
}

struct ContentView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        let someView = UIView(frame: UIScreen.main.bounds)
        _ = someView.takeScreenshot()
        return someView
    }

    func updateUIView(_ view: UIView, context: Context) {

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案没有用——他问如何将 SwiftUI 视图渲染到图像,这个答案展示了如何将 UIView 渲染到图像。该答案不应被标记为已接受。 (4认同)
  • 恕我直言,您的答案是生成一个尺寸与屏幕尺寸相同的空白白色图像。虽然我一直在寻求一种方法来生成内容超出屏幕尺寸的视图图像。这就是我一直在问的问题,甚至在我添加示例之前的问题的原始版本中也是如此。 (2认同)