How to make a screenshot of all the content of a Scrollview?

前端 未结 1 1010
北恋
北恋 2021-01-02 04:22

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

相关标签:
1条回答
  • 2021-01-02 05:13

    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:

    0 讨论(0)
提交回复
热议问题