UIView take a screenshot when it is not visible

I have a UIView that can be drawn like a finger paint application, but sometimes it is not visible. I want to be able to take a screenshot of it when it is not visible. Also, I want a screenshot where it is visible, but I don’t want any subviews. I just want the UIView itself. This is the method I have tried:

func shapshot() -> UIImage? {
    UIGraphicsBeginImageContext(self.frame.size)
    guard let context = UIGraphicsGetCurrentContext() else {
        return nil
    }
    self.layer.render(in: context)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    if image == nil {
        return nil
    }

    return image
}

func snapshot() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(bounds.size, self.isOpaque, UIScreen.main.scale)
    layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

Source: Swift Questions