簡體   English   中英

如何將 SwiftUI 圖像保存到磁盤或獲取數據?

[英]How can I save a SwiftUI image to disk or get the data out?

我正在嘗試將 SwiftUI 圖像(不是來自 UIKit 的 UIImage)保存到磁盤。

我到處找,但找不到任何有關如何執行此操作的文檔信息。 我也看不到從 SwiftUI 圖像中提取數據的方法。

有人可以幫忙嗎? 提前致謝。

使用 SwiftUI,事情會有所不同。 你想做的事,不能那樣做。 相反,您需要查看圖像是如何創建的,並從您的Image()最初獲得它的同一個地方獲取圖像數據。

此外,如果您需要實際的二進制數據將其保存到磁盤,則需要一個UIImage (請注意,我不是說UIImageView )。

幸運的是,Image 也可以處理UIImage ,檢查另一個問題: https : //stackoverflow.com/a/57028615/7786555

我將 SwiftUI 圖像轉換為 UIImage,然后將其保存到 UserDefaults。

這不是最好的解決方案,但我沒有找到更好的解決方案:

   // reading the saved image from userDefaults
   private func getSavedImage(for size: String) -> Image? {
    if let data = UserDefaults.standard.data(forKey: size) {
        if let image = UIImage(data: data) {
            return Image(uiImage: image)
        }
    }
    return nil
  }



// Converting SwiftUI Image to UIImage
extension View {

    public func toUIImage() -> UIImage {

        let controller = UIHostingController(rootView: self)
        controller.view.frame = CGRect(x: 0, y: CGFloat(Int.max), width: 1, height: 1)
        #if targetEnvironment(macCatalyst)

            UIApplication.shared.windows.first!.rootViewController?.view.addSubview(controller.view)

        #else

        var window: UIWindow? {
            guard let scene = UIApplication.shared.connectedScenes.first,
                  let windowSceneDelegate = scene.delegate as? UIWindowSceneDelegate,
                  let window = windowSceneDelegate.window else {
                return nil
            }
            return window
        }

        if let window = window, let rootViewController = window.rootViewController {
                var topController = rootViewController
                while let newTopController = topController.presentedViewController {
                    topController = newTopController
                }
            topController.view.insertSubview(controller.view, at: controller.view.subviews.count)
        } else {
            print("cant access window")
        }

        #endif

        let size = controller.sizeThatFits(in: UIScreen.main.bounds.size)
        controller.view.bounds = CGRect(origin: .zero, size: size)
        controller.view.sizeToFit()

        // here is the call to the function that converts UIView to UIImage: `.asImage()`
        let image = controller.view.toUIImage()
        controller.view.removeFromSuperview()
        return image
    }
}

使用頂級助手並保存圖像:

extension Image {
    
func toData()-> Data {
    return self.toUIImage().jpegData(compressionQuality: 1)!
}

func save(for name: String) {
        UserDefaults.standard.setValue(self.toData(), forKey: name)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM