0

Note: iOS 13

For below code:

extension UIScrollView {

    var snapshot: UIImage? {
        UIGraphicsBeginImageContextWithOptions(contentSize, false, 0)
        defer {
            UIGraphicsEndImageContext()
        }
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        let previousFrame = frame
        let previousOffset = contentOffset
        frame = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height)
        contentOffset = CGPoint.zero
        layer.render(in: context)
        frame = previousFrame
        contentOffset = previousOffset
        return UIGraphicsGetImageFromCurrentImageContext()
    }

}

It did work perfect in iOS 12, however, only snapshot part of (visible area) scrollView in iOS 13.

I want to snapshot total scrollView.Any way to solve it?

无夜之星辰
  • 5,426
  • 4
  • 25
  • 48
  • You already posted pretty much the same topic several hours ago, didn't you? Why are you doing it repeatedly? – El Tomato Jul 08 '20 at 06:24
  • @ElTomato I had deleted that post, it's not so clear.And I didn't find the way to solve this problem so I need some help. – 无夜之星辰 Jul 08 '20 at 06:28
  • I don't think that's possible. You may have to create a `UIView` object manually and add smaller objects to it for yourself. – El Tomato Jul 08 '20 at 06:39
  • plz check this one https://stackoverflow.com/questions/41920416/how-to-make-a-screenshot-of-all-the-content-of-a-scrollview – Jins George Jul 08 '20 at 06:40
  • Does this answer your question? [How to make a screenshot of all the content of a Scrollview?](https://stackoverflow.com/questions/41920416/how-to-make-a-screenshot-of-all-the-content-of-a-scrollview) – Mehdi Gilanpour Jul 08 '20 at 08:02

1 Answers1

0

The key to solving the problem is to removeFromSuperview at first :

private func snapshot() -> UIImage? {
    
    // remove first
    scrollView.removeFromSuperview()
    
    UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, false, 0)
    
    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()
    
    // add again
    self.view.addSubview(scrollView)
    
    scrollView.snp.remakeConstraints { (make) in
        make.left.right.equalToSuperview()
        make.top.equalTo(naviHeight)
        make.bottom.equalTo(-safeBottomHeight-105)
    }
    
    return image
}

Interesting...

无夜之星辰
  • 5,426
  • 4
  • 25
  • 48