1

I would like to generate some images dynamicaly. For that, I intend to create a XAML View, populate it with Data (using DataBinding) and then generate an image from the rendering of that view (kind of a screenshot).

Is there a way to do this in Silverligth or WPF?

Emond
  • 50,210
  • 11
  • 84
  • 115
AbdouMoumen
  • 3,814
  • 1
  • 19
  • 28

3 Answers3

7

In WPF:

public static Image GetImage(Visual target)
{
    if (target == null)
    {
        return null; // No visual - no image.
    }
    var bounds = VisualTreeHelper.GetDescendantBounds(target);

    var bitmapHeight = 0;
    var bitmapWidth = 0;

    if (bounds != Rect.Empty)
    {
        bitmapHeight = (int)(Math.Floor(bounds.Height) + 1);
        bitmapWidth = (int)(Math.Floor(bounds.Width) + 1);
    }

    const double dpi = 96.0;

    var renderBitmap =
        new RenderTargetBitmap(bitmapWidth, bitmapHeight, dpi, dpi, PixelFormats.Pbgra32);

    var visual = new DrawingVisual();
    using (var context = visual.RenderOpen())
    {
        var brush = new VisualBrush(target);
        context.DrawRectangle(brush, null, new Rect(new Point(), bounds.Size));
    }

    renderBitmap.Render(visual);

    return new Image
    {
        Source = renderBitmap,
        Width = bitmapWidth,
        Height = bitmapHeight
    };
}
Pavlo Glazkov
  • 20,498
  • 3
  • 58
  • 71
1

Use the WriteableBitmap and its Render function in Silverlight.

In WPF use this trick by using the RenderTargetBitmap and its Render function

Emond
  • 50,210
  • 11
  • 84
  • 115
0

You can add the controls (data after they are databound) that you want to capture to a ViewBox - http://www.wpftutorial.net/ViewBox.html

From there, you can create an image using WriteableBitmap - http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap%28VS.95%29.aspx

njebert
  • 534
  • 4
  • 14