我有一个带有ScrollViewer控件的WPF窗口,其中包含许多垂直扩展的子控件.当用户单击位于ScrollViewer底部的按钮时,我希望将所有内容(当前在视图中和视图外)保存为图像.
我正在使用以下代码,我从示例中修改了如何保存窗口内容:
public static void SaveForm(ScrollViewer container, string filename)
{
const int dpi = 96;
var rtb = new RenderTargetBitmap(
(int)container.ExtentWidth, //width
(int)container.ExtentHeight, //height
dpi, //dpi x
dpi, //dpi y
PixelFormats.Pbgra32 // pixelformat
);
rtb.Render(container);
SaveRTBAsPNG(rtb, filename);
}
private static void SaveRTBAsPNG(RenderTargetBitmap bmp, string filename)
{
var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
using (var stm = System.IO.File.Create(filename))
{
enc.Save(stm);
}
}
Run Code Online (Sandbox Code Playgroud)
目前正在生产PNG,但它只有ScrollViewer的当前可见部分.有什么方法可以让PNG包含所有内容,包括需要滚动到视图中的内容吗?
小智 10
使用此滚动查看器的内容作为源,而不是滚动查看器本身:(即使内容不可见,它也会拍摄快照)
public static void SnapShotPNG(this UIElement source, Uri destination, int zoom)
{
try
{
double actualHeight = source.RenderSize.Height;
double actualWidth = source.RenderSize.Width;
double renderHeight = actualHeight * zoom;
double renderWidth = actualWidth * zoom;
RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32);
VisualBrush sourceBrush = new VisualBrush(source);
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
using (drawingContext)
{
drawingContext.PushTransform(new ScaleTransform(zoom, zoom));
drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight)));
}
renderTarget.Render(drawingVisual);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderTarget));
using (FileStream stream = new FileStream(destination.LocalPath, FileMode.Create, FileAccess.Write))
{
encoder.Save(stream);
}
}
catch (Exception e)
{
MessageBox.Show(e);
}
}
Run Code Online (Sandbox Code Playgroud)