Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight 4 - Render UIElement as an Image

I have a UIElement that I want to capture a snapshot of when a user clicks a button. When a user clicks the button, I want to take the UIElement and load it's current state into an Image element. How do I render a UIElement as an Image?

like image 399
user208662 Avatar asked May 06 '10 20:05

user208662


2 Answers

Assuming the FrameworkElement you want to render is named elementToRender and the Image where you want to place the rendered output is called image, use the following code on your button's click handler:

var writeableBitmap = new WriteableBitmap((int)elementToRender.RenderSize.Width, (int)elementToRender.RenderSize.Height);

writeableBitmap.Render(elementToRender, new ScaleTransform() { ScaleX = 1, ScaleY = 1 });
writeableBitmap.Invalidate();

image.Source = writeableBitmap;
like image 166
Bruno Avatar answered Nov 23 '22 00:11

Bruno


You can also do the following:

private void SetImageSourceBasedOnElement(Image image, UIElement element)
{
    if (element != null)
    {
        WriteableBitmap writableBitmap = new WriteableBitmap(element, null);
        writableBitmap.Invalidate();

        image.Source = writableBitmap;
     }
 }
like image 26
MyKuLLSKI Avatar answered Nov 23 '22 00:11

MyKuLLSKI