如何在Swift中的UITableView中截取所选行的屏幕截图并将其保存为UIImage?

时间:2017-04-15 20:50:03

标签: ios swift uitableview swift3 uiimage

在我的git clone my_users_repo应用中,我有Swift包含4个静态单元格,然后它有不同数量的动态单元格。我只想截取静态单元的截图。

我找到了以下扩展名:

UITableView

它来自这个问题How to render a whole UITableView as an UIImage in iOS?

但问题是,即使我改变了:

extension UITableView {
    var capturedImage : UIImage {
        UIGraphicsBeginImageContext(contentSize);
        scrollToRow(at: NSIndexPath(row: 0, section: 0) as IndexPath, at:     UITableViewScrollPosition.top, animated: false)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let row = numberOfRows(inSection: 0)
        let numberofRowthatShowinscreen = 4
        let scrollCount = row / numberofRowthatShowinscreen

        for i in 0 ..< scrollCount  {
            scrollToRow(at: NSIndexPath(row: (i+1)*numberofRowthatShowinscreen, section: 0) as     IndexPath, at: UITableViewScrollPosition.top, animated: false)
            layer.render(in: UIGraphicsGetCurrentContext()!)
        }

        let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext();
        return image;
    }
}

为:

let numberofRowthatShowinscreen = 4

然后它仍然会截取整个let numberofRowthatShowinscreen = 3 的屏幕截图。有没有办法将它限制在前4行呢?

1 个答案:

答案 0 :(得分:1)

在示例代码中,您将在图像上下文中呈现表视图的图层。这将始终快照整个表视图。您可以在快照之前获取评论者的建议并调整表格视图的单元格。或者,您可以快照要渲染的单元格的图层。例如:

extension UITableView
{
    func snapshotRows(at indexPaths: Set<IndexPath>) -> UIImage?
    {
        guard !indexPaths.isEmpty else { return nil }
        var rect = self.rectForRow(at: indexPaths.first!)
        for indexPath in indexPaths
        {
            let cellRect = self.rectForRow(at: indexPath)
            rect = rect.union(cellRect)
        }

        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        for indexPath in indexPaths
        {
            let cell = self.cellForRow(at: indexPath)
            cell?.layer.bounds.origin.y = self.rectForRow(at: indexPath).origin.y - rect.minY
            cell?.layer.render(in: context)
            cell?.layer.bounds.origin.y = 0
        }

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

用法:

let image = tableView.snapshotRows(at: Set([IndexPath(row: 0, section: 0), IndexPath(row: 0, section: 1)]))

只会快照特定的细胞。正如另一篇文章的答案所说,这只适用于重复使用细胞的可见细胞。