AbdouMoumen
AbdouMoumen

Reputation: 3854

Generate image from XAML View

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?

Upvotes: 1

Views: 2884

Answers (3)

Pavlo Glazkov
Pavlo Glazkov

Reputation: 20746

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
    };
}

Upvotes: 7

njebert
njebert

Reputation: 544

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

Upvotes: 0

Emond
Emond

Reputation: 50672

Use the WriteableBitmap and its Render function in Silverlight.

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

Upvotes: 1

Related Questions