Skip to content

Instantly share code, notes, and snippets.

@DominatorVbN
Created May 14, 2020 19:41
Show Gist options
  • Save DominatorVbN/edb4a772918daddd74637fda73c5e453 to your computer and use it in GitHub Desktop.
Save DominatorVbN/edb4a772918daddd74637fda73c5e453 to your computer and use it in GitHub Desktop.
import UIKit
import SwiftUI
import PlaygroundSupport
extension UIView {
var renderedImage: UIImage {
// rect of capure
let rect = self.bounds
// create the context of bitmap
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
let context: CGContext = UIGraphicsGetCurrentContext()!
self.layer.render(in: context)
// get a image from current context bitmap
let capturedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return capturedImage
}
}
extension View {
func takeScreenshot(origin: CGPoint, size: CGSize) -> UIImage {
let window = UIWindow(frame: CGRect(origin: origin, size: size))
let hosting = UIHostingController(rootView: self)
hosting.view.frame = window.frame
window.addSubview(hosting.view)
window.makeKeyAndVisible()
return hosting.view.renderedImage
}
}
class ImageStore: ObservableObject ,Identifiable{
let id = UUID()
var image: UIImage
init(image: UIImage){
self.image = image
}
}
struct ContentView: View{
@State var imageStore: ImageStore?
var body: some View{
NavigationView{
GeometryReader{ geo in
ZStack{
LinearGradient(gradient: Gradient(colors: [Color.blue,Color.white]), startPoint: .top, endPoint: .bottom)
Button(action: {
self.genImage(geo: geo)
}, label: {
Text("Create Image")
.foregroundColor(.white)
})
}
}
}
.sheet(item: $imageStore) { store in
Image(uiImage: store.image)
}
}
func genImage(geo: GeometryProxy){
let image = self.takeScreenshot(origin: geo.frame(in: .global).origin, size: geo.size)
self.imageStore = ImageStore(image: image)
}
}
PlaygroundPage.current.setLiveView(ContentView())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment