2

I have multiple subviews on a parent view, and I need to convert the uiview to a uiimage but of only certain subviews. So I added a tag to the views I needed to take a screenshot of and added it to its own view, but when I try to screenshot that I get a black screen. However, when I use the regular parent view I get a photo with all the subviews.

let viewPic = UIView()

            for subview in self.view.subviews {

                if(subview.tag == 6) {
                    viewPic.addSubview(subview)
                }

                if(subview.tag == 8) {
                    viewPic.addSubview(subview)
                }
            }

            let picImage = viewPic.getSnapshotImage() //This is a black screen

getSnapshotImage

extension UIView {
    public func getSnapshotImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0)
        self.drawHierarchy(in: self.bounds, afterScreenUpdates: false)
        let snapshotItem: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return snapshotItem
    }
}
joethemow
  • 1,641
  • 4
  • 24
  • 39
  • Refer from this answer, it might help you [iOS Screenshot part of the screen](http://stackoverflow.com/questions/12687909/ios-screenshot-part-of-the-screen) – iDevAmit Apr 07 '17 at 09:44

1 Answers1

0

First of all, your viewPic doesn't set the frame size so the default will be zero frame which may cause the issue.

Secondly, I tried to use your getSanpshotImage() on my sample project, but I always get the blank image.

Have a look at the demo code, I can get what you want (see the screenshot):

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let viewPic = UIView()
        viewPic.frame = self.view.frame

        let view1 = UIView()
        view1.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        view1.backgroundColor = UIColor.red
        viewPic.addSubview(view1)

        let view2 = UIView()
        view2.frame = CGRect(x: 0, y: 200, width: 100, height: 100)
        view2.backgroundColor = UIColor.blue
        viewPic.addSubview(view2)

        let picImage = viewPic.convertToImage() //This is a black screen
        print(picImage)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

extension UIView {
    func convertToImage() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
}

enter image description here

brianLikeApple
  • 4,262
  • 1
  • 27
  • 46