4

There are a lot of ways to take a screengrab of a UIView. The de facto way to capture a UIView "screengrab" of a UIView is snapshotViewAfterScreenUpdates which returns a UIReplicantView (subclass of UIView).

Is there a way to create a UIImage from this seemingly recalcitrant class?

Community
  • 1
  • 1
Warpling
  • 2,024
  • 2
  • 22
  • 38

1 Answers1

0

This is the extension we used to capture UIView into UIImageView. The solution doesn't contain any usage of UIReplicatView as you suggested. But it has been working great for us:

extension UIView {
    // Note: only return the image after viewDidAppear called
    func takeScreenShot() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, UIScreen.main.scale)

        if let scrollView = self as? UIScrollView {
            let offset = scrollView.contentOffset
            UIGraphicsGetCurrentContext()?.translateBy(x: -offset.x, y: -offset.y);
        }

        drawHierarchy(in: bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}
Yuchen
  • 30,852
  • 26
  • 164
  • 234