我想从视图中创建PNG。我正在使用此代码:
//I instance the user control
ucFormToPrintView miViewToPrint = new ucFormToPrintView();
miViewToPrint.DataContext = ((ucFormToPrintView)CCForm).DataContext;
//I use a RenderTargetBitmap to render the user control
System.Windows.Media.Imaging.RenderTargetBitmap rtb = new System.Windows.Media.Imaging.RenderTargetBitmap(794, 1122, 72, 72, System.Windows.Media.PixelFormats.Pbgra32);
rtb.Render(miViewToPrint);
//I use an encoder to create the png
System.Windows.Media.Imaging.PngBitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));
//I use a dialog to select the path where to save the png file
Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
saveFileDialog.FilterIndex = 1;
if (saveFileDialog.ShowDialog() == true)
{
using (System.IO.Stream stream = saveFileDialog.OpenFile())
{
encoder.Save(stream);
stream.Close();
System.Diagnostics.Process.Start(saveFileDialog.FileName);
}
}
结果是一个空的png。
如何从用户控件创建png文件?
非常感谢。
答案 0 :(得分:1)
UserControl必须至少布局一次才能看到。您可以通过调用Measure
和Arrange
方法来实现这一目标。
var miViewToPrint = new ucFormToPrintView();
miViewToPrint.DataContext = ((ucFormToPrintView)CCForm).DataContext;
// layout, i.e. measure and arrange
miViewToPrint.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
miViewToPrint.Arrange(new Rect(miViewToPrint.DesiredSize));
...
if (saveFileDialog.ShowDialog() == true)
{
using (var stream = saveFileDialog.OpenFile())
{
encoder.Save(stream);
}
System.Diagnostics.Process.Start(saveFileDialog.FileName);
}