在通用应用程序中捕获当前网站的屏幕截图
本文关键字:网站 屏幕截图 应用程序 | 更新日期: 2023-09-27 18:25:42
以下是我如何捕捉当前网页的屏幕截图,但有时它只捕捉网络视图的可见区域(用户实际看到的内容)。但我不确定出了什么问题。我认为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;
}
Github 上的测试存储库
最后问题本身是在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;
}