Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to draw a wpf control to memory (Bitmap) without drawing on the screen at all?
I found an example of how to save to Bitmap, but it only works when the window has been drawn in the screen.

BitmapImage bitmap = new BitmapImage();
    RenderTargetBitmap renderTarget =
    new RenderTargetBitmap((int)canvaspad.Width,
    (int)canvaspad.Height,
    96,
    96,
    System.Windows.Media.PixelFormats.Default);
renderTarget.Render(canvaspad);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
268 views
Welcome To Ask or Share your Answers For Others

1 Answer

As the control has no parent container, you need to call Measure and Arrange in order to do a proper layout. As layout is done asynchronously (see Remarks in Measure and Arrange), you may also need to call UpdateLayout to force the layout to be updated immediately.

public BitmapSource RenderToBitmap(UIElement element, Size size)
{
    element.Measure(size);
    element.Arrange(new Rect(size));
    element.UpdateLayout();

    var bitmap = new RenderTargetBitmap(
        (int)size.Width, (int)size.Height, 96, 96, PixelFormats.Default);

    bitmap.Render(element);
    return bitmap;
}

In case you have already set the Width and Height of the element you may use that for the size parameter:

var grid = new Grid
{
    Width = 200,
    Height = 200,
    Background = Brushes.Yellow
};

grid.Children.Add(
    new Ellipse
    {
        Width = 100,
        Height = 100,
        Fill = Brushes.Blue
    });

var bitmap = RenderElement(grid, new Size(grid.Width, grid.Height));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...