Some technical things, mostly odd happenings from a remote office RSS Feed


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, 9696PixelFormats.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, 500500, 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(00500500));

// generate image from XAML element
SaveImage(button, 500500, filePath); 


 
Posted by Ralph Arvesen | 2 Comments | Trackback Url | Bookmark with:        
Tags:

Links to this Post

Comments

Tuesday, 19 Jan 2010 05:25 by Tom Glenn
It might be worth noting that this doesn't work in Silverlight. :(

Name:
URL:
Email:
Comments:

CAPTCHA Image Validation