I am trying to share an image of a view through the Share Sheet. This is what i am doing.
One defines an extension to UIView and View where one utilizes the UIGraphicsImageRenderer to output an UIImage and modifies the .asImage to output the picture as an UIImage.
It seems to me the simplest approach to making it work. But the image is not showing in the ShareSheet.
import SwiftUI
struct SnapshottingAPI: View {
@State private var isShareSheetShowing = false
let imageSize: CGSize = CGSize(width: 1000, height: 1000)
var body: some View {
VStack {
ZStack {
Color.blue
Circle()
.fill(Color.red)
}
.frame(width: 300, height: 300)
Text("text")
Button(action: shareButton){
Image(systemName: "square.and.arrow.up")
.frame(width: 35, height: 35)
}
}
}
func shareButton() {
isShareSheetShowing.toggle()
let highresImage = self.asImage(size: imageSize)
let outputimage = Image(uiImage: highresImage)
let items: [Any] = [outputimage]
let av = UIActivityViewController(activityItems: items, applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController!.present(av, animated: true, completion: nil)
}
}
extension UIView {
func asImage() -> UIImage {
let format = UIGraphicsImageRendererFormat()
format.scale = 1
return UIGraphicsImageRenderer(size: self.layer.frame.size, format: format).image { context in
self.drawHierarchy(in: self.layer.bounds, afterScreenUpdates: true)
}
}
}
extension View {
func asImage(size: CGSize) -> UIImage {
let controller = UIHostingController(rootView: self)
controller.view.bounds = CGRect(origin: .zero, size: size)
let image = controller.view.asImage()
return image
}
}
struct SnapshottingAPI_Previews: PreviewProvider {
static var previews: some View {
SnapshottingAPI()
}
}