首页 > 解决方案 > 如何wpf画布背景连续更改图像

问题描述

当我将 WebBrowser 控件的地图屏幕保存为图像文件并将图像文件指定为 Canvas 控件的背景时。当我按下按钮时,WebBrowser Visibility Hidden and show Canvas 显示保存的地图图像,再次显示 WebBrowser,然后 Canvas Visibility Hidden,保存图像,并在 Canvas 中显示图像,但第二次尝试是由于错误. 我想知道如何解决 Canvas 的资源问题。背景。

[xml]

    <Grid>
        <WebBrowser x:Name="mapScript" 
                    Source="http://localhost/test.html" 
                    LoadCompleted="mapScript_LoadCompleted">
        </WebBrowser>
        <Canvas Name="canvas" Visibility="Hidden"></Canvas>
    </Grid>

[xaml.cs]

保存 WebBrowser 图像并显示 Cavnas 按钮(WebBrowser 隐藏、画布显示)

    private void MapMoveStop(object sender, RoutedEventArgs e)
    {
        object xy = mapScript.InvokeScript("mapDragStop");

        var topLeftCorner = mapScript.PointToScreen(new System.Windows.Point(0, 0));
        var topLeftGdiPoint = new System.Drawing.Point((int)topLeftCorner.X, (int)topLeftCorner.Y);
        var size = new System.Drawing.Size((int)mapScript.ActualWidth, (int)mapScript.ActualHeight);
        Bitmap screenShot = new Bitmap((int)mapScript.ActualWidth, (int)mapScript.ActualHeight);
        using (var graphics = Graphics.FromImage(screenShot))
        {
            graphics.CopyFromScreen(topLeftGdiPoint, new System.Drawing.Point(), size, CopyPixelOperation.SourceCopy);
        }
        canvas.Background = new ImageBrush();
        screenShot.Save(@"D:\Temp\tmp.png");

        mapScript.Visibility = Visibility.Collapsed;
        canvas.Visibility = Visibility.Visible;
        mapImageCanvas.Visibility = Visibility.Visible;

        ImageBrush ib = new ImageBrush();
        ib.ImageSource = new BitmapImage(new Uri(@"D:\Temp\tmp.png", UriKind.Relative));
        canvas.Background = ib;
    }

[xaml.cs]

显示 WebBrowser 和隐藏画布按钮

    private void MapMoveStart(object sender, RoutedEventArgs e)
    {
        object xy = mapScript.InvokeScript("mapDragStart");

        mapScript.Visibility = Visibility.Visible;
        canvas.Visibility = Visibility.Hidden;

        ImageBrush ib = new ImageBrush();
        ib.ImageSource = new BitmapImage(new Uri(@"D:\Temp\tmp2.png", UriKind.Relative));
        canvas.Background = ib;

    }

[错误信息]

System.Runtime.InteropServices.ExternalException:'GDI+

我怀疑Canvas的背景有图片,并没有放出这个资源。ScreenShot.Save(@"D:\Temp\tmp.png"); 在执行代码时尝试保存 tmp png 似乎是一个问题。所以,要初始化画布 ScreenShot.Above Save() Canvas 的背景。背景 = 新的 ImageBrush(); 放入代码这不会解决它。

标签: c#wpf

解决方案


推荐阅读