Snapshot of XAML control, save to image
You
can use the
RenderTargetBitmap class to generate an image from a
UI element. For
example, say you want to generate an image from the XAML
element ThePanel.
<StackPanel Name="ThePanel" Orientation="Horizontal">
<Rectangle Width="50" Height="50" Fill="Red" />
<Rectangle Width="50" Height="50" Fill="Orange" />
<Rectangle Width="50" Height="50" Fill="YellowGreen" />
</StackPanel>
You can use RenderTargetBitmap to generate an
image,
and PngBitmapEncode
to save to a PNG file.
void SaveImage(Visual visual, int width, int height, string filePath)
{
// generate the image
RenderTargetBitmap bitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(visual);
// create image file
PngBitmapEncoder image = new PngBitmapEncoder();
image.Frames.Add(BitmapFrame.Create(bitmap));
using (Stream fs = File.Create(filePath))
{
image.Save(fs);
}
}
Calling
the
SaveImage method.
// full path to the image
string filePath = Path.Combine(System.Environment.CurrentDirectory, "sample.png");
// generate image from XAML element
SaveImage(this.ThePanel, 500, 500, filePath);
If you are creating the control dynamically, be sure to call Arrange
on
the control before generating the image.
// full path to the image
string filePath = Path.Combine(System.Environment.CurrentDirectory, "sample.png");
// create instance of control
Button button = new Button();
button.Content = "Nifty Button";
// layout control before generating image
button.Arrange(new Rect(0, 0, 500, 500));
// generate image from XAML element
SaveImage(button, 500, 500, filePath);