How to take screenshot of UIScrollView visible area?

前端 未结 8 1659
鱼传尺愫
鱼传尺愫 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:35

    Swift version of Abduliam Rehmanius answer.

    func screenshot() -> UIImage {
    
            UIGraphicsBeginImageContextWithOptions(self.scrollCrop.bounds.size, true, UIScreen.mainScreen().scale);
            //this is the key
            let offset:CGPoint = self.scrollCrop.contentOffset;
            CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -offset.x, -offset.y);
            self.scrollCrop.layer.renderInContext(UIGraphicsGetCurrentContext()!);
            let visibleScrollViewImage: UIImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return visibleScrollViewImage;
        }
    

    Swift 4 version:

    func screenshot() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.scrollCrop.bounds.size, false, UIScreen.main.scale)
            let offset = self.scrollCrop.contentOffset
            let thisContext = UIGraphicsGetCurrentContext()
            thisContext?.translateBy(x: -offset.x, y: -offset.y)
            self.scrollCrop.layer.render(in: thisContext!)
            let visibleScrollViewImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    return visibleScrollViewImage
    }
    

提交回复
热议问题