Created
December 28, 2020 02:23
-
-
Save SlappyAUS/6ce4911d97cbfb4846169ac7e240f602 to your computer and use it in GitHub Desktop.
Save SwiftUI View as Image #swift #swifui #image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
func convertViewToData<V>(view: V, size: CGSize, completion: @escaping (Data?) -> Void) where V: View { | |
guard let rootVC = UIApplication.shared.windows.first?.rootViewController else { | |
completion(nil) | |
return | |
} | |
let imageVC = UIHostingController(rootView: view.edgesIgnoringSafeArea(.all)) | |
imageVC.view.frame = CGRect(origin: .zero, size: size) | |
DispatchQueue.main.async { | |
rootVC.view.insertSubview(imageVC.view, at: 0) | |
let uiImage = imageVC.view.asImage(size: size) | |
imageVC.view.removeFromSuperview() | |
completion(uiImage.pngData()) | |
} | |
} | |
extension UIView { | |
func asImage(size: CGSize) -> UIImage { | |
let format = UIGraphicsImageRendererFormat() | |
format.scale = 1 | |
return UIGraphicsImageRenderer(size: size, format: format).image { context in | |
layer.render(in: context.cgContext) | |
} | |
} | |
} | |
struct ContentView: View { | |
@State var imageData: Data? | |
var body: some View { | |
VStack { | |
if let imageData = imageData, let uiImage = UIImage(data: imageData) { | |
Image(uiImage: uiImage) | |
} | |
} | |
.onAppear { | |
convertViewToData(view: ViewToRender(textValue: "🐻"), size: .init(width: 300, height: 300)) { | |
imageData = $0 | |
} | |
} | |
Button("Export", action: export) | |
} | |
func export() { | |
if let img = imageData, let image = UIImage(data: img), let data = image.pngData() { | |
let filename = getDocumentsDirectory().appendingPathComponent("copy.png") | |
print("Exported: \(filename)") | |
try? data.write(to: filename) | |
} | |
} | |
func getDocumentsDirectory() -> URL { | |
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) | |
return paths[0] | |
} | |
} | |
struct ViewToRender: View { | |
let textValue: String | |
var body: some View { | |
ZStack { | |
Color.blue | |
Circle() | |
.fill(Color.red) | |
Text("\(textValue)") | |
.font(.system(size: 200)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment