1

I have got a UITableView, and I want to capture the visible portion of it, and put it into a UIImage. Any way of doing this?

EDIT

Self-answered below

cannyboy
  • 24,180
  • 40
  • 146
  • 252

4 Answers4

6

Thanks for the replies. All of the answers would work with a UIView, but not with a UITableView - at least not when the table has scrolled. When scrolled, the captured image would appear black or transparent. I had tried similar solutions as the ones below before. I guess people assumed the answer was obvious, and that's why I was down-voted - for being naughty enough to ask such an obvious question.

Anyway, the real solution is that you have to use the table's contentOffset:

- (UIImage *) imageWithTableView:(UITableView *)tableView
{
    UIView *renderedView = tableView;
    CGPoint tableContentOffset = tableView.contentOffset;
    UIGraphicsBeginImageContextWithOptions(renderedView.bounds.size, renderedView.opaque, 0.0);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(contextRef, 0, -tableContentOffset.y);
    [tableView.layer renderInContext:contextRef];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
cannyboy
  • 24,180
  • 40
  • 146
  • 252
3
UIGraphicsBeginImageContext(someView.bounds.size);
[someView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Taken from this question.

Community
  • 1
  • 1
deanWombourne
  • 38,189
  • 13
  • 98
  • 110
1
- (UIImage *)captureView {

//hide controls if needed
CGRect rect = [yourTableView bounds];

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [yourTableview.layer renderInContext:context];   
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;

}
Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
1
UIGraphicsBeginImageContext(tableView.bounds.size);
[tableView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Maybe those posts will be helpful Rendering UIView with its children

Saving UIView contents in iOS 4 with real size of the images inside (i.e. scale contentes up for save)

Safe way to render UIVIew to an image on background thread?

Community
  • 1
  • 1
BergP
  • 3,453
  • 4
  • 33
  • 58