将wpf视图保存为图像,最好是.png

Kia*_*eng 8 c# wpf mvvm c#-4.0

我已经搜索并了解如何使用在WPF中保存图像BmpBitmapEncoder.我的程序有一个MVVM视图,我想保存为图像.是否可以将其设置为BitmapFrame可以对其进行编码?如果是这样,是否有在线教程?

下面列出的是我想要保存的视图.

 <Grid>
        <view:OverallView Grid.Row="1"
                      Visibility="{Binding IsOverallVisible,Converter={StaticResource B2VConv}}"
                      />
    </Grid>
Run Code Online (Sandbox Code Playgroud)

OverallView 是一个用户控件.


如果将视图设置为a,BitmapFrame则可以将哪些wpf元素设置为BitmapSource/Frame

小智 20

您可以将其作为RenderTargetBitmap返回:

public static RenderTargetBitmap GetImage(OverallView view)
{
    Size size = new Size(view.ActualWidth, view.ActualHeight);
    if (size.IsEmpty)
        return null;

    RenderTargetBitmap result = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);

    DrawingVisual drawingvisual = new DrawingVisual();
    using (DrawingContext context = drawingvisual.RenderOpen())
    {
        context.DrawRectangle(new VisualBrush(view), null, new Rect(new Point(), size));
        context.Close();
    }

    result.Render(drawingvisual);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

之后,您可以使用PngBitmapEncoder将其保存为PNG并将其保存为流,例如:

public static void SaveAsPng(RenderTargetBitmap src, Stream outputStream)
{
    PngBitmapEncoder encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(src));

    encoder.Save(outputStream);   
}
Run Code Online (Sandbox Code Playgroud)

FIX:位图=>结果