2016-11-04 28 views
1

我正在使用以下代碼來抓取我的視圖的屏幕截圖。afterScreenUpdates時drawHierarchy失敗:true

UIGraphicsBeginImageContext(self.view.bounds.size) 
self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: true) 
let wholeImage = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 

如果我將「afterScreenUpdates:」設置爲false,它會正常工作。但是,如果我把它設置爲true,我得到以下錯誤:

*** Assertion failure in -[UIApplication _performWithUICACommitStateSnapshotting:](), /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3600.5.2/UIApplication.m:6882 

使用斷點,我發現該錯誤的drawHierarchy方法拋出。任何人以前看過這個錯誤?任何想法發生了什麼?我已經嘗試在抓取快照之前取出視圖的任何更新(隱藏一些uiimages),但它沒有效果。

奇怪的一面是:應用程序凍結這個錯誤,但沒有硬停(我不能與調試器交互來查看回溯)。對不起,如果這不清楚。

回答

1

我也有這個錯誤。問題是iOS中的所有UIKit工作都需要在主線程上完成。快速解決方案是將其包裝在主線程的DispatchQueue.async調用中:

var wholeImage : UIImage? 

DispatchQueue.main.async { 
    UIGraphicsBeginImageContext(self.view.bounds.size) 
    self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: true) 
    self.wholeImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 
} 
相關問題