How to render a whole UITableView as an UIImage in iOS?

后端 未结 13 2164
太阳男子
太阳男子 2020-12-17 23:54

I have simple UITableView with some data. The table\'s height is greater than the screen size. Now I need to catch screenshot of this table (a whole table). I k

13条回答
  •  佛祖请我去吃肉
    2020-12-18 00:37

    add render method to UITableView through category

    - (UIImage *)render {
    
        //save the origin infos for later to restore
        CGPoint originContentOffset = self.contentOffset;
    
        //force jump to table view's top
        self.contentOffset = CGPointZero;
    
        UIGraphicsBeginImageContext(self.contentSize);
    
        CGContextRef *ctx = UIGraphicsGetCurrentContext();
    
        //render header 
        [self.tableHeaderView.layer renderInContext:ctx];
    
        //render sections
        NSInteger numberOfSections = [self numberOfSections];
        for (int section = 0; section < numberOfSections; section++) {
            NSInteger numberOfRows = [self numberOfRowsInSection:section];
            for (int row = 0; row < numberOfRows; row++) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
                //check cell is visible
                if ([self cellForRowAtIndexPath:indexPath]) {
                    [self scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:false];
                    [self.layer renderInContext:ctx];
                }
            }
        }
    
        //render footer
        [self.tableFooterView.layer renderInContext:ctx];
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        //restore infos
        self.contentOffset = originContentOffset;
    
        return image;
    }
    

提交回复
热议问题