简体   繁体   中英

Swift 3 - How to take a screenshot of specific UITableView row

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.

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM