Re: [問題] UITableView截圖

看板MacDev作者 (白毛)時間11年前 (2014/01/09 15:06), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/1
後來試了三種寫法 最後一種寫法效能最好 但是也遇到一些問題, 詳見方法三(附Demo 影片 & github) 方法一: 1.把tableView.frame展開成跟contentSize一樣的大小, 2.再用tableView.layer renderInContext:...... 但是如果tableView展開太大的話 效能會奇差無比 因為沒有reuse cell 必需把所有cell都畫到tableView上 方法二: (方法一的改良版) 1.把tableView.frame展開成欲截圖範圍的大小, 而不是contentSize的大小(改善效能的關鍵) 2.設contentOffset 或用 scrollToRowAtIndexPath: 把bounds移到欲截圖的範圍 3.一樣用tableView.layer renderInContext:.... , 但是只有欲截圖的範圍(bounds的範圍)會被畫在context上, 其它部分則是空白的 4.再用CGImageCreateWithImageInRect把context上面的截圖部分(非空白部分)取出 雖然效能提昇了, 但如果欲截圖的範圍太大, 一樣會變很慢 worst case: 欲截圖範圍為整個tableView的contentSize 方法三: (效能最佳版) 1.針對欲截圖範圍的每個cell, 依序使用[tableView scrollToIndexPath: 將bounds移動到該處, 使cell可以被畫在tableView上 2.再用cell.layer renderInContext 3.使用CGContextTranslateCTM移動context的origin至下次要render cell的原點 總而言之 此做法的概念為: 依序一個一個把cell render到context上 目前遇到一個問題 我的cell裡有UITextView 如果截圖範圍超出tableView的height 截下來的圖, 有部分的textView.text會重覆 只有UITextView會有這種情況, 其它如UIButton, UITextField都是正常的 請看Demo影片 (按下play鍵後可能要等一下) http://screencast.com/t/jpZNcETe Demo project https://github.com/WhiteFur/ScreenshotTableViewDemo 重點程式碼 - 截圖 //indexPaths為欲截圖的cells - (UIImage*)screenShotForIndexPaths:(NSArray*)indexPaths { CGPoint originalOffset = self.tableView.contentOffset; //產生欲截圖範圍size的context, width為tableView的width, height為欲截圖的cells的total height UIGraphicsBeginImageContextWithOptions(CGSizeMake(CGRectGetWidth(self.tableView.frame), self.tableView.rowHeight * [indexPaths count]), NO, 0.0); CGContextRef ctx = UIGraphicsGetCurrentContext(); //---一個一個把cell render到CGContext上 MyTableViewCell *cell = nil; for(NSIndexPath *indexPath in indexPaths) { //讓該cell被正確的產生在tableView上, 之後才能在CGContext上正確的render出來 [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO]; cell = (MyTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath]; [cell.layer renderInContext:ctx]; //--欲在context上render的origin CGContextTranslateCTM(ctx, 0, self.tableView.rowHeight); //-- } //--- UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); self.tableView.contentOffset = originalOffset; return image; } 以上,非常感謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 110.29.193.144 ※ 編輯: whitefur 來自: 110.29.193.144 (01/09 15:09) ※ 編輯: whitefur 來自: 110.29.193.144 (01/09 15:10) ※ 編輯: whitefur 來自: 110.29.193.144 (01/09 15:10) ※ 編輯: whitefur 來自: 110.29.193.144 (01/09 15:33)
文章代碼(AID): #1Ipag6BA (MacDev)
文章代碼(AID): #1Ipag6BA (MacDev)