开发者

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 renderin开发者_开发技巧g of that view (kind of a screenshot).

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


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


Use the WriteableBitmap and its Render function in Silverlight.

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜