将文本转换为png图像SwiftUI

时间:2020-10-25 20:41:30

标签: swiftui

面对您需要通过按下按钮将Texteditor中写入的所有内容转换为图像的事实。例如,即使文本包含多行并且在滚动时屏幕上也消失了。告诉我如何在swiftUI上实现它?

我当前正在使用此代码:

public struct ScreenshotableView<Content: View>: View {
    @Binding var shotting: Bool
    @Binding var toCopy: Bool
    var completed: (UIImage) -> Void
    var toCopyCompleted: (UIImage) -> Void
    let content: Content
    
public init(shotting:Binding<Bool>,toCopy:Binding<Bool> , completed: @escaping (UIImage) -> Void,toCopyCompleted: @escaping (UIImage) -> Void, @ViewBuilder content: () -> Content) {
    self._shotting = shotting
    self._toCopy = toCopy
    self.completed = completed
    self.toCopyCompleted = toCopyCompleted
    self.content = content()
}
    
public var body: some View {
    
    func internalView(proxy: GeometryProxy) -> some View {
        if self.shotting {
            let frame = proxy.frame(in: .local)
            DispatchQueue.main.async {
                let screenshot = self.content.takeScreenshot(frame: frame, afterScreenUpdates: true)
                self.completed(screenshot)
            }
        }
        return Color.clear
    }
    
    return content.background(GeometryReader(content: internalView(proxy:)))
}

public extension View {
func takeScreenshot(frame:CGRect, afterScreenUpdates: Bool) -> UIImage {
    let hosting = UIHostingController(rootView: self)
    hosting.overrideUserInterfaceStyle = UIApplication.shared.windows.first?.overrideUserInterfaceStyle ?? UIUserInterfaceStyle.unspecified
    hosting.view.frame = frame
    return hosting.view.takeScreenshot(afterScreenUpdates: afterScreenUpdates)
}


public extension UIView {
func takeScreenshot() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0)
    self.layer.render(in: UIGraphicsGetCurrentContext()!)
    let snapshot = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return snapshot!
}

func takeScreenshot(afterScreenUpdates: Bool) -> UIImage {
    if !self.responds(to: #selector(drawHierarchy(in:afterScreenUpdates:))) {
        return self.takeScreenshot()
    }
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0)
    let draw = self.drawHierarchy(in: self.bounds, afterScreenUpdates: afterScreenUpdates)
    print(draw)
    let snapshot = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return snapshot!
}

}

但是这里的屏幕快照仅是从可见部分获得的,不包括滚动

0 个答案:

没有答案