Search code examples
swiftuiscrollviewscreenshot

Take screenshot of visible area of UIScrollView


I have a UIScrollView as subview of a view controller main view. I'm trying to save a screenshot of whatever is visible in the frame of the UIScrollView only.

UIGraphicsBeginImageContextWithOptions(imageScrollView.bounds.size, false, UIScreen.main.scale) let context = UIGraphicsGetCurrentContext() context?.translateBy(x: 0, y: 0)

    view.layer.render(in: context!)
    let visibleScrollViewImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()


    let popupImageView = UIImageView(image: visibleScrollViewImage)
    popupImageView.layer.borderColor = UIColor.white.cgColor
    popupImageView.layer.borderWidth = 4
    popupImageView.frame = CGRect(origin: CGPoint(x: 0, y: 400), size: CGSize(width: 400, height: 400))

    imageScrollView.removeFromSuperview()

    view.addSubview(popupImageView)

The part with the popupImageView is just to test out and see what is actually saving, it seems there is some offset problem, the horizontal axis is fine but i seem to be getting just the top third of the image I want, and above that is just dark space.

Seems like it must be a pretty easy solution but I've searched through all similar questions and can't find an answers.

Thanks heaps!


Solution

  • Try the following. If I do it with a UITableView control, it works.

    import UIKit
    
    class ViewController: UIViewController {
        @IBAction func snapTapped(_ sender: UIButton) {
            UIGraphicsBeginImageContextWithOptions(imageScrollView.bounds.size, true, 1.0)
            imageScrollView.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: imageScrollView.bounds.size), afterScreenUpdates: true)
            if let image = UIGraphicsGetImageFromCurrentImageContext() {
                UIGraphicsEndImageContext()
                myImageView.image = image
            }
        }
    }