SwiftUI

SwiftUI中 屏幕截图

  • SceneDelegate中得到window对象
import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView()

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            //定义windowComm变量保存window对象
            windowComm = window
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            
            window.makeKeyAndVisible()
        }
    }
  • SwiftUI中调用的例子
struct xxxxelView: View {
    var isTakeSnapPhoto = NotificationCenter.default.publisher(for: .takeSnapPhoto)
    var body: some View {
        VStack(spacing: 0) {
          
        }.onReceive(isTakeSnapPhoto) { _ in
  
            let screenRect = UIScreen.main.bounds
                UIGraphicsBeginImageContext(screenRect.size)
                let ctx: CGContext = UIGraphicsGetCurrentContext()!
                windowComm!.layer.render(in: ctx)
                let image = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext();
        }
    }

}