Swift 3 - 如何截取特定 UITableView 行的屏幕截图 [英] Swift 3 - How to take a screenshot of specific UITableView row
问题描述
我需要有一个特定 UITableView 行的屏幕截图,并在屏幕截图之前删除/添加内容到单元格.
I need to have a screenshot of a specific UITableView row and remove/add content to the cell before the screenshot.
例如:单元格只包含一个文本和一个分享按钮.单击共享按钮时,我希望应用生成一个图像,顶部带有 文本 和我的应用 徽标(没有分享按钮).
For example: the cell contains only a text and a share button. On share button click, I want the app to generate an image with the text and my app logo on the top (without the share button).
这样做的最佳方法是什么?以及如何?
What is the best approach to do this? and how?
提前致谢.
推荐答案
@Nirav 在评论区已经给你提示了:
如何截取 UIView 的一部分?
@Nirav already gave you a hint in the comment section with this post:
How to take screenshot of portion of UIView?
因此,您现在必须在超级视图中获取单元格的 Rect,因此我制作了一个示例操作方法:
So, you have now to get the Rect of the cell in the superview, so i made a sample action method:
@IBOutlet var snapImageView: UIImageView!
@IBAction func snapshotrow(_ sender: Any) {
//get the cell
if let cell = myTable.cellForRow(at: IndexPath(row: 0, section: 0)) as? MyCustomCellClass {
//hide button
cell.shareButton.isHidden = true
let rectOfCellInTableView = myTable.rectForRow(at: IndexPath(row: 0, section: 0))
let rectOfCellInSuperview = myTable.convert(rectOfCellInTableView, to: myTable.superview)
snapImageView.image = self.view.snapshot(of: rectOfCellInSuperview)
let finalImage = saveImage(rowImage: snapImageView.image)
//test final image
snapViewImage.image = finalImage
}
}
func saveImage(rowImage: UIImage) -> UIImage {
let bottomImage = rowImage
let topImage = UIImage(named: "myLogo")!
let newSize = CGSize.init(width: 41, height: 41) // set this to what you need
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
bottomImage.draw(in: CGRect(origin: .zero, size: newSize))
topImage.draw(in: CGRect(origin: .zero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
并且我能够获取表格视图的第 0 个单元格的快照并将其分配给 snapImageView
.
and I was able to get the snapshot of the 0th cell of my table view and assigned it to the snapImageView
.
现在最后一步是将图像保存到相机胶卷中,SO 中有很多相关的帖子.
Now the last step is to save the image to the camera roll, there are lots of related post out there in SO.
添加标志和隐藏分享按钮:保存一个Swift 中另一张图片上的图片
Adding logo and hiding share button: Saving an image on top of another image in Swift
这篇关于Swift 3 - 如何截取特定 UITableView 行的屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!