How to take screenshot of UIScrollView visible area?

前端 未结 8 1616
鱼传尺愫
鱼传尺愫 2021-02-13 16:57

How do I take a 1:1 screenshot of UIScrollView visible area? The content may be larger or smaller than UIScrollView bounds as well as half-hidden (I\'ve implemented custom scrol

相关标签:
8条回答
  • 2021-02-13 17:48

    Swift 4 version of Abduliam Rehmanius answer as UIScrollView extension with translation, no slow cropping

    extension UIScrollView {
    
        var snapshotVisibleArea: UIImage? {
            UIGraphicsBeginImageContext(bounds.size)
            UIGraphicsGetCurrentContext()?.translateBy(x: -contentOffset.x, y: -contentOffset.y)
            layer.render(in: UIGraphicsGetCurrentContext()!)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    }
    
    0 讨论(0)
  • 2021-02-13 17:48

    Swift 3.0 :

     func captureScreen() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.yourScrollViewName.bounds.size, true, UIScreen.main.scale)
        let offset:CGPoint = self.yourScrollViewName.contentOffset;
        UIGraphicsGetCurrentContext()!.translateBy(x: -offset.x, y: -offset.y);
        self.yourScrollViewName.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    

    and use it as : let Image = captureScreen()

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