Getting a screenshot of a UIScrollView, including offscreen parts

前端 未结 12 2121
遥遥无期
遥遥无期 2020-11-22 17:31

I have a UIScrollView decendent that implements a takeScreenshot method that looks like this:

-(void)takeScreenshot {  
  CGRect contextRect  =          


        
12条回答
  •  北海茫月
    2020-11-22 18:01

    Working Example of UIView Extension with handling for UIScrollView:

    extension UIView {
        func screenshot() -> UIImage {
    
                if(self is UIScrollView) {
                    let scrollView = self as! UIScrollView
    
                    let savedContentOffset = scrollView.contentOffset
                    let savedFrame = scrollView.frame
    
                    UIGraphicsBeginImageContext(scrollView.contentSize)
                    scrollView.contentOffset = .zero
                    self.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)
                    self.layer.render(in: UIGraphicsGetCurrentContext()!)
                    let image = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext();
    
                    scrollView.contentOffset = savedContentOffset
                    scrollView.frame = savedFrame
    
                    return image!
                }
    
                UIGraphicsBeginImageContext(self.bounds.size)
                self.layer.render(in: UIGraphicsGetCurrentContext()!)
                let image = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                return image!
    
            }
    }
    

提交回复
热议问题