我正在尝试将整个 UIWebView(甚至是屏幕外的内容)捕获到 PNG。以下代码在大多数设备上运行良好,但在某些 iPad 1st gens 上它在此行上崩溃:
[self.webview.layer renderInContext:resizedContext]; /// crash
如何通过停止 renderInContext 进程来防止崩溃?
有关问题的上下文,请参见下面的代码示例:
//Create original tmp bounds
CGRect tmpFrame = self.webview.frame;
CGRect tmpBounds = self.webview.bounds;
CGRect aFrame = self.webview.bounds;
aFrame.size.width = self.webview.frame.size.width;
aFrame.size.height = self.webview.frame.size.height;
self.webview.frame = aFrame;
aFrame.size.height = [self.webview sizeThatFits:[[UIScreen mainScreen] bounds].size].height;
NSLog(@"webpage size %f",self.webview.frame.size.height);
self.webview.frame = aFrame;
UIGraphicsBeginImageContext([self.webview sizeThatFits:[[UIScreen mainScreen] bounds].size]);
CGContextRef resizedContext = UIGraphicsGetCurrentContext();
// crash
[self.webview.layer renderInContext:resizedContext]; // crash
// crash
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.webview.frame = tmpFrame;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",@"TestImage"]];
NSError *error;
[UIImagePNGRepresentation(image) writeToFile:pngPath options:NSDataWritingAtomic error:&error];
NSURL *url = [NSURL fileURLWithPath:pngPath];
//reset webview
self.webview.bounds = tmpBounds;
self.webview.frame = tmpFrame;
模拟器不会崩溃,以下是在设备上运行时来自控制台的日志记录错误:
May 16 12:33:41 unknown SpringBoard[29] <Warning>: Application 'AppName' exited abnormally with signal 11: Segmentation fault: 11
May 16 12:33:41 unknown DTMobileIS[652] <Warning>: _memoryNotification : {
OSMemoryNotificationLevel = 0;
timestamp = "2012-05-16 19:33:41 +0000";
}
May 16 12:33:41 unknown DTMobileIS[652] <Warning>: _memoryNotification : <NSThread: 0x1d5286d0>{name = (null), num = 1}
May 16 12:33:41 unknown DTMobileIS[652] <Warning>: _memoryNotification : {
OSMemoryNotificationLevel = 0;
timestamp = "2012-05-16 19:33:41 +0000";
}