自定义表格单元格并将表格单元格导出为png文件

时间:2013-02-01 12:52:00

标签: iphone ios xcode ipad uitableview

我希望有一个应用程序,当我在一些表格单元格中输入大量数据时。然后,所有数据将汇总在最下面的表格单元格中。 (我已经这样做了。)

我的问题是如何将最低或任何特定的表格单元格专门导出为PNG格式作为图像?

我尝试过使用打印屏幕,但它不是很好,而且设备数量也各不相同。有没有我只能导出该单元格的代码?

谢谢

1 个答案:

答案 0 :(得分:4)

// Specify your index path
NSUInteger index[] = {0, 1}; // section, row
NSIndexPath *indexPath = [[NSIndexPath alloc] initWithIndexes:index length:2];

// Get the cell
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

// Render a graphics context to turn your cell into a UIImage
CGSize imageSize = cell.bounds.size;
UIGraphicsBeginImageContext(imageSize);
CGContextRef imageContext = UIGraphicsGetCurrentContext();
[cell.layer renderInContext:imageContext];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Save the image as PNG
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *dest = [docDir stringByAppendingPathComponent:@"image.png"];
[UIImagePNGRepresentation(image) writeToFile:dest atomically:YES];

修改

要获得更精确的单元格快照,可以使用单元格的contentView属性,即

[cell.contentView.layer renderInContext:imageContext];