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

后端 未结 13 2165
太阳男子
太阳男子 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:23

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.tableView.contentSize.width, self.tableView.contentSize.height), YES, 0);
    
    CGFloat originY = 0;
    
    CGRect rectFirst =  CGRectMake(0, originY, self.tableView.bounds.size.width, self.view.bounds.size.height);
    
    [self.tableView scrollRectToVisible:rectFirst animated:NO];
    
    [self.tableView drawViewHierarchyInRect:rectFirst afterScreenUpdates:true];
    
    while (originY < self.tableView.contentSize.height) {
    
       CGRect rectSecond =  CGRectMake(0, originY, self.tableView.bounds.size.width, self.view.bounds.size.height);
    
        [self.tableView scrollRectToVisible: rectSecond animated:NO];
    
        [self.tableView drawViewHierarchyInRect: rectSecond afterScreenUpdates:true];
    
        originY += self.view.bounds.size.height;
    
    }
    
    CGRect rectFinally =  CGRectMake(0, originY, self.tableView.bounds.size.width, self.tableView.contentSize.height - originY);
    
    [self.tableView scrollRectToVisible:rectFinally animated:NO];
    
    [self.tableView drawViewHierarchyInRect:rectFinally afterScreenUpdates:true];
    
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();  
    
    UIGraphicsEndImageContext();
    

    It's very important to set animated to NO, and don't block the UI thread

提交回复
热议问题