Swift 3 - How to take a screenshot of specific UIT

2020-08-05 10:07发布

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?

Thanks in advance.

1条回答
ゆ 、 Hurt°
2楼-- · 2020-08-05 10:38

@Nirav already gave you a hint in the comment section with this post:
How to take screenshot of portion of UIView?

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
}

and I was able to get the snapshot of the 0th cell of my table view and assigned it to the snapImageView.

Now the last step is to save the image to the camera roll, there are lots of related post out there in SO.

Source: Get Cell position in UITableview

Adding logo and hiding share button: Saving an image on top of another image in Swift

查看更多
登录 后发表回答