給UITableViewCell截屏是一個比較普通的需求,代碼如下:
func takeScreenshot(cell: UITableViewCell) -> UIImage {
UIGraphicsBeginImageContextWithOptions(cell.bounds.size, true, UIScreen.main.scale)
cell.drawHierarchy(in: cell.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return image
}
但是,如果傳入的cell不在屏幕中時,截圖會失敗。解決方案是:
- 記錄下當(dāng)前UITableView的contentOffset
- 手動計算出目標(biāo)cell的IndexPath。這里要注意,不能使用tableView.indexPath(for: cell)。因為目標(biāo)cell在屏幕外,此函數(shù)會返回nil。
- 利用該IndexPath將目標(biāo)cell移動到屏幕中
- 調(diào)用takeScreenshot函數(shù)截屏
- 根據(jù)記錄下的contentOffset,再將UITableView移動回原來的位置
代碼如下:
func screenshot(cell: UITableViewCell) -> UIImage {
// model.indexPathFor(cell:) 是從本地數(shù)據(jù)中算出目標(biāo)cell的IndexPath的方法
guard let indexPath = model.indexPathFor(cell: UITableViewCell) else {
return UIImage()
}
let currentOffset = tableView.contentOffset
tableView.scrollToRow(at: indexPath, at: .top, animated: false)
let image = takeScreenShot(cell: cell)
tableView.setContentOffset(currentOffset, animated: false)
return image
}