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

问题描述 投票:0回答:1

在我的Swift应用程序中,我有一个包含4个静态细胞的UITableView,然后它有不同数量的动态细胞。我想仅截取静态单元的截图。

我找到了以下扩展名:

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;
    }
}

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

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

let numberofRowthatShowinscreen = 4

至:

let numberofRowthatShowinscreen = 3

然后它仍然需要整个UITableView的截图。有没有办法将它限制在前4行呢?

ios swift uitableview swift3 uiimage
1个回答
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)]))

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

© www.soinside.com 2019 - 2024. All rights reserved.