Search code examples
swiftimagescreenshotuiactivityviewcontrolleruigraphicscontext

Screenshot by programming turns black - Swift


I am trying to share a screenshot from my game through UIUIActivityViewController. To do this, I am creating a screenshot programatically and passes it through the UIActivityViewController.

The ActivityViewController seems to work. However, the image is all black.

Here is my code, were do I miss?

UIGraphicsBeginImageContextWithOptions(view!.frame.size, false, 0.0)
view!.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

let shareViewController = UIActivityViewController(activityItems: [image], applicationActivities: [])
MenuScene.parentView.present(shareViewController, animated: true, completion: nil)

The MenuScene.parentView is the GameViewController.


Solution

  • So I changed the code to the following, with great results.

                let bounds = UIScreen.main.bounds
                UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
                yourUIViewController.view!.drawHierarchy(in: bounds, afterScreenUpdates: false)
    
                let img = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
    
                let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
    

    And of course, presenting the view.

    yourUIViewController.present(activityViewController, animated: true, completion: nil)