如何将 WebViewBrush 保存为图像?(UWP/通用) [英] How to save WebViewBrush as image? (UWP / Universal)

查看:30
本文介绍了如何将 WebViewBrush 保存为图像?(UWP/通用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总结:我有一个集合 FrameworkElements(基本上是在矩形上绘制的 web 视图画笔),我想将其中的每一个保存为一个 PNG 文件在我的UWP 应用.

Summary: I have a collection FrameworkElements (basically web view brushes drawn on rectanlges), and I'd like to save each of these as a PNG file in my UWP app.

更多详细信息:我按照 https://stackoverflow.com/a/17222629/上的示例进行操作2884981 将 WebView 的内容拆分为单独的页面".

More details: I followed the example at https://stackoverflow.com/a/17222629/2884981 to split the content of a WebView into separate "pages".

我已将主要代码放在底部.

I've put the main bits of code at the bottom.

GetWebPages() 的底部,我有 return pages;在这一点上,我有一个所有页面"的列表.

At the bottom of GetWebPages() I have return pages; At this point I have a list of all the "pages".

我想做的是将这些页面中的每一个都转换为图像(例如,到最后我会有一组 PNG 文件).

What I'd like to do, is then convert each of those pages into an image (so by the end of it I'd have a collection of PNG files, for instance).

有谁知道我该怎么做?提前致谢.

Does anyone know how I can do this? Thanks in advance.

    public async Task<WebViewBrush> GetWebViewBrush(WebView webView)
    {
        // resize width to content
        double originalWidth = webView.Width;
        var widthString = await webView.InvokeScriptAsync("eval", new[] { "document.body.scrollWidth.toString()" });
        int contentWidth;

        if (!int.TryParse(widthString, out contentWidth))
        {
            throw new Exception(string.Format("failure/width:{0}", widthString));
        }

        webView.Width = contentWidth;

        // resize height to content
        double originalHeight = webView.Height;
        var heightString = await webView.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" });
        int contentHeight;

        if (!int.TryParse(heightString, out contentHeight))
        {
            throw new Exception(string.Format("failure/height:{0}", heightString));
        }

        webView.Height = contentHeight;

        // create brush
        var originalVisibilty = webView.Visibility;
        webView.Visibility = Windows.UI.Xaml.Visibility.Visible;

        WebViewBrush brush = new WebViewBrush
        {
            SourceName = webView.Name,
            Stretch = Stretch.Uniform
        };

        brush.Redraw();

        // reset, return
        webView.Width = originalWidth;
        webView.Height = originalHeight;
        webView.Visibility = originalVisibilty;

        return brush;
    }

还有:

        public async Task<IEnumerable<FrameworkElement>> GetWebPages(WebView webView, Windows.Foundation.Size page)
        {
            // ask the content its width
            var widthString = await webView.InvokeScriptAsync("eval", new[] { "document.body.scrollWidth.toString()" });
            int contentWidth;

            if (!int.TryParse(widthString, out contentWidth))
            {
                throw new Exception(string.Format("failure/width:{0}", widthString));
            }

            webView.Width = contentWidth;

            // ask the content its height
            var heightString = await webView.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" });
            int contentHeight;

            if (!int.TryParse(heightString, out contentHeight))
            {
                throw new Exception(string.Format("failure/height:{0}", heightString));
            }

            webView.Height = contentHeight;

            // how many pages will there be?
            double scale = page.Width / contentWidth;
            double scaledHeight = (contentHeight * scale);
            double pageCount = (double) scaledHeight / page.Height;
            pageCount = pageCount + ((pageCount > (int) pageCount) ? 1 : 0);

            // create the pages
            var pages = new List<Windows.UI.Xaml.Shapes.Rectangle>();

            for (int i = 0; i < (int)pageCount; i++)
            {
                var translateY = -page.Height * i;

                var rectanglePage = new Windows.UI.Xaml.Shapes.Rectangle
                {
                    Height = page.Height,
                    Width = page.Width,
                    Margin = new Thickness(5),
                    Tag = new TranslateTransform { Y = translateY },
                };

                rectanglePage.Loaded += (async (s, e) =>
                {
                    var subRectangle = s as Windows.UI.Xaml.Shapes.Rectangle;
                    var subBrush = await GetWebViewBrush(webView);
                    subBrush.Stretch = Stretch.UniformToFill;
                    subBrush.AlignmentY = AlignmentY.Top;
                    subBrush.Transform = subRectangle.Tag as TranslateTransform;
                    subRectangle.Fill = subBrush;
                });

                pages.Add(rectanglePage);
            }

            return pages;
        }

推荐答案

我想在我的 UWP 应用中将其中的每一个保存为一个 PNG 文件.

I'd like to save each of these as a PNG file in my UWP app.

你可以在WebViewNavigationCompleted事件的ItemsControl中获取所有的矩形并显示它们,如下所示:

You can get all the rectangles and show them in the ItemsControl in the NavigationCompleted event of WebView like this:

private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    MyWebViewRectangle.Fill = await GetWebViewBrush(webView);
    MyPrintPages.ItemsSource = await GetWebPages(webView, new Windows.Foundation.Size(842, 595));
}

然后在按钮单击事件中,您可以将所有项目保存为 .png 图像,如下所示:

Then in a button click event you can save all the items as .png images like this:

private async void Savetoimage_Clicked(object sender, RoutedEventArgs e)
{
    var piclib = Windows.Storage.KnownFolders.PicturesLibrary;
    foreach (var item in MyPrintPages.Items)
    {
        var rect = item as Rectangle;
        RenderTargetBitmap renderbmp = new RenderTargetBitmap();
        await renderbmp.RenderAsync(rect);
        var pixels = await renderbmp.GetPixelsAsync();
        var file = await piclib.CreateFileAsync("webview.png", Windows.Storage.CreationCollisionOption.GenerateUniqueName);
        using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
            byte[] bytes = pixels.ToArray();
            encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                             BitmapAlphaMode.Ignore,
                             (uint)rect.Width, (uint)rect.Height,
                             0, 0, bytes);
            await encoder.FlushAsync();
        }
    }
}

这篇关于如何将 WebViewBrush 保存为图像?(UWP/通用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆