本文介绍了将WPF视图另存为图像,最好保存为.png的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have searched and understand how to save an image in WPF by using BmpBitmapEncoder. My program has a MVVM view that I want to save as an image. Is it possible to set it as BitmapFrame so I can encode it? If so, is there an online tutorial?

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

Listed below is the view I want to save.

 <Grid>
        <view:OverallView Grid.Row="1"
                      Visibility="{Binding IsOverallVisible,Converter={StaticResource B2VConv}}"
                      />
    </Grid>

OverallView 是用户控件。

如果无法将视图设置为 BitmapFrame ,wpf元素可以设置为 BitmapSource / Frame

If setting a view as a BitmapFrame is not possible, what wpf elements can be set as a BitmapSource/Frame?

推荐答案

返回为:

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;
}

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

After that you can use the PngBitmapEncoder to save it as PNG and save it to stream, e.g.:

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

    encoder.Save(outputStream);
}

FIX:位图=>结果

FIX: bitmap => result

这篇关于将WPF视图另存为图像,最好保存为.png的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 01:05