如何将整个可滚动的 UITableView 保存为 PNG

How to save the whole scrollable UITableView to PNG

我想将整个 UITableView 保存到一个 PNG 文件中。

通过这段代码,我设法保存了可见部分:

UIGraphicsBeginImageContextWithOptions(tableView.layer.frame.size, false, 0.0);
tableView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let data = UIImagePNGRepresentation(image)
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let imageURL = documentsURL.URLByAppendingPathComponent("cached.png")
data!.writeToURL(imageURL, atomically: false)

但我也想要目前未显示的可滚动部分。

有什么想法吗?

这里有一些 Swift extensions files 您可以添加到您的项目中以制作屏幕截图:

新代码为:

let image = tableView.screenshot
let data = UIImagePNGRepresentation(image)
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let imageURL = documentsURL.URLByAppendingPathComponent("cached.png")
data!.writeToURL(imageURL, atomically: false)