我无法捕捉到WKWebView的截图
我试图捕获一个WKWebView的截图,但我的方法无法正常工作,它返回一个纯色,就像图层树是空的,而它似乎在其他视图上工作。
- (UIImage *)screenshot { UIImage *screenshot; UIGraphicsBeginImageContext(self.frame.size); [self.layer renderInContext:UIGraphicsGetCurrentContext()]; screenshot = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return screenshot; }
这个Stackoverflow答案解决了我在iOS 8与WKWebView其中[view snapshotViewAfterScreenUpdates:]
和[view.layer renderInContext:]
返回纯黑色或白色:
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0); [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES]; UIImage* uiImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
WKWebView仍然存在一个错误,但是你可以使用另一个函数来解决它:
[webView snapshotViewAfterScreenUpdates:NO or YES];
有用。
drawViewHierarchyInRect方法将工作,但会导致屏幕短暂闪烁。
如果您需要高性能(快速捕捉多个帧),我build议将WKWebView添加到您的窗口某处(即使您使用帧偏移将它推出可见区域或使其透明)。 我发现renderInContext要快得多,只要视图在窗口的视图层次结构中就可以正常工作。
这是我的两点。 在iOS 10.3.1之前, renderInContext
用于WKWebView。 但只有当一个WKWebView被包含在一个呈现的视图层次结构中。 换句话说,系统正在屏幕上绘制它。
在iOS 10.3.1中, renderInContext
不适用于我。 同时, drawViewHierarchyInRect
在iOS 10.3.1中正常工作。 但只有当它在视图层次结构中! 更糟。 当我试图获取当前屏幕上未显示的WKWebView的快照时,原始视图变为无效。 因此,截图可以打破一个WKWebView。
这是我的解决方法。
- 每次我需要的时候,我都会用
drawViewHierarchyInRect
保存一个快照(UIImage
)。 但只有当WKWebView在屏幕上。 - 如果WKWebView不在视图层次结构中,则使用保存的快照。
尝试这个
- (IBAction)takeScreenShot:(id)sender { UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow]; CGRect rect = [keyWindow bounds]; UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); [keyWindow.layer renderInContext:context]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil); } - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { // Was there an error? if (error != NULL) { // Show error message... UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Image not Saved" message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alertView show]; } else // No errors { // Show message image successfully saved UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Image Saved" message:@"This chart has been save to your photos" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alertView show]; } }