Created
May 14, 2020 19:41
-
-
Save DominatorVbN/edb4a772918daddd74637fda73c5e453 to your computer and use it in GitHub Desktop.
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 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