I want to create a screenshot of a UIScrollView
which should contain the whole content of the scroll view, even that content, which is currently not visible to
To Swift from this answer, adding a test ViewController:
class ScreenShotTestViewController: UIViewController {
var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView = UIScrollView(frame: CGRect(origin: CGPoint.zero, size: view.frame.size))
scrollView.contentSize = CGSize(width: view.frame.size.width, height: view.frame.size.height * 2)
scrollView.backgroundColor = UIColor.yellow
view.addSubview(scrollView)
let label = UILabel(frame: CGRect(x: 0.0, y: view.frame.size.height * 1.5, width: view.frame.size.width, height: 44.0))
label.text = "Hello World!"
scrollView.addSubview(label)
let screenShot = snapshot()
}
func snapshot() -> UIImage?
{
UIGraphicsBeginImageContext(scrollView.contentSize)
let savedContentOffset = scrollView.contentOffset
let savedFrame = scrollView.frame
scrollView.contentOffset = CGPoint.zero
scrollView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)
scrollView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
scrollView.contentOffset = savedContentOffset
scrollView.frame = savedFrame
UIGraphicsEndImageContext()
return image
}
}
Results in an image of the complete content, including subviews: