Screenshot from a UITableView

Viewed 8553

I know there are many questions about this theme but I really read all of them but not found an answer.

I want make a screenshot from the current table view. and i do it this way:

-(UIImage *)imageFromCurrentView
{
    UIGraphicsBeginImageContextWithOptions(self.tableView.bounds.size, YES, 1);
    [self.tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Everything works fine, but when i scroll down in the tableview and make the screenshot, half of the image is black. I don't know how to make the screenshot from the actual tableview area.

7 Answers

This will get you the current visible region of the TableView.

If you want to render the entire tableview, first you need to be aware thats probably not a great idea for anything more than a few dozen rows because of memory and what not. The max image size in 2048x2048 so your tableView can be no taller than that.

UIView *viewToRender = self.tableView;
CGPoint contentOffset = self.tableView.contentOffset;

UIGraphicsBeginImageContext(viewToRender.bounds.size);

CGContextRef ctx = UIGraphicsGetCurrentContext();

//  KEY: need to translate the context down to the current visible portion of the tablview
CGContextTranslateCTM(ctx, 0, -contentOffset.y);

[viewToRender.layer renderInContext:ctx];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

take a look at this library I made to do exactly this, it has very useful methods like:

  1. Take a full screenshot of your UITableView (all the cells are rendered on a single UIImage)
  2. Take a screenshot for just a single cell given its indexPath
  3. Take a screenshot of just the headers, footers or rows of your UITableView

And more...

You can add it to your project via Cocoapods or manually by dragging the Source files.

The usage is so simple:

UIImage * tableViewScreenshot = [self.tableView screenshot];

I hope you find this library helpful as much as I do.

For Swift 5 you can use this code

    let viewToRender = tableView;
    let contentOffset = tableView.contentOffset

    UIGraphicsBeginImageContext(viewToRender.bounds.size)

    if let ctx = UIGraphicsGetCurrentContext() {
       ctx.translateBy(x: 0, y: -contentOffset.y)

       viewToRender.layer.render(in: ctx)

       let image = UIGraphicsGetImageFromCurrentImageContext();

    }
    UIGraphicsEndImageContext();
Related