以下是我如何捕捉当前网页的屏幕截图,但有时它只捕获webview的可见区域(用户实际看到的内容)。
但我不确定是什么问题。
我认为var heightString = await WebView.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" })
已经太晚了 - 但程序应该在if (!int.TryParse(heightString, out height))
等待完成......我错了吗?
private async Task CaptureWebView()
{
int width;
int height;
var originalWidth = WebView.Width;
var originalHeight = WebView.Height;
// ask the content its width
var widthString = await WebView.InvokeScriptAsync("eval", new[] { "document.body.scrollWidth.toString()" });
// ask the content its height
var heightString = await WebView.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" });
if (!int.TryParse(widthString, out width))
{
throw new Exception("Unable to get page width");
}
if (!int.TryParse(heightString, out height))
{
throw new Exception("Unable to get page height");
}
// resize the webview to the content
WebView.Width = width;
WebView.Height = height;
await DoCapture("captured.png");
WebView.Width = originalWidth;
WebView.Height = originalHeight;
Painter.Width = width;
Painter.Height = height;
var i = await LoadCaptured("captured.png");
Painter.Fill = i;
}
测试存储库on Github
答案 0 :(得分:3)
最后问题本身就是WebView.CapturePreviewToStreamAsync()
方法。我用它来捕捉完整的网页截图,但它并没有很好地工作。但后来我发现WebViewBrush
并意识到这是正确的方法。
所以这里是最终的代码段或GitHub
private async Task CaptureWebView()
{
int width;
int height;
var originalWidth = WebView.ActualWidth;
var originalHeight = WebView.ActualHeight;
var widthString = await WebView.InvokeScriptAsync("eval", new[] { "document.body.scrollWidth.toString()" });
var heightString = await WebView.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" });
if (!int.TryParse(widthString, out width))
{
throw new Exception("Unable to get page width");
}
if (!int.TryParse(heightString, out height))
{
throw new Exception("Unable to get page height");
}
// resize the webview to the content
WebView.Width = width;
WebView.Height = height;
var brush = new WebViewBrush();
brush.SetSource(WebView);
Painter.Width = width;
Painter.Height = height;
Painter.Fill = brush;
}