将SwiftUI视图渲染为UIImage

问题描述 投票:1回答:1

我正在尝试将SwiftUI视图呈现为UIImage,然后保存到相机胶卷中。过去几周通过互联网搜索仍然没有运气。我尝试了2种不同的方法。

1。 UIHostingController([source here

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

我已经尝试过layoutSubviews()setNeedsLayout()layoutIfNeeded()loadView(),但所有结果仍然有0个子视图。

2。 UIWindow.rootViewController([source here

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

这几乎产生了我想要的输出。但是,我得到的快照实际上是屏幕截图,即具有导航栏,标签栏和固定大小(与屏幕大小相同)。我需要捕获的只是没有这些条的视图内容,有时可能比屏幕大(在这种情况下,我的视图是垂直滚动视图)。

试图查询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>>]

非常感谢您的帮助。

ios xcode render swiftui snapshot
1个回答
2
投票

这样的东西对您有用吗?

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()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.