Force rendering of a WPF control in memory

前端 未结 2 887
滥情空心
滥情空心 2020-11-30 04:14

I have the following code:

void Test()
{
    currentImage.Source = GetBitmap();
    RenderTargetBitmap rtb = new RenderTargetBitmap(100, 100, 96.0, 96.0, Pix         


        
相关标签:
2条回答
  • 2020-11-30 04:46

    use a ViewBox to render in memory

    Grid grid = new System.Windows.Controls.Grid() { Background = Brushes.Blue, Width = 200, Height = 200 };
    Viewbox viewbox = new Viewbox();
    viewbox.Child = grid; //control to render
    viewbox.Measure(new System.Windows.Size(200, 200));
    viewbox.Arrange(new Rect(0, 0, 200, 200));
    viewbox.UpdateLayout();
    RenderTargetBitmap render = new RenderTargetBitmap(200, 200, 150, 150, PixelFormats.Pbgra32);
    render.Render(viewbox);
    
    0 讨论(0)
  • 2020-11-30 04:50

    I think this is a BETTER answer .
    The viewbox didn't work completely as expected, and it turned out to be an unnecessary overhead.

    Here is a copy of that answer (instead of just link)


    You need to force a render of the item, or wait for the item to be rendered. You can then use the ActualHeight and ActualWidth properties.

    To force a render:

      MenuItem item = new MenuItem();
      item.Header = "bling";
      item.Icon = someIcon;
      //Force render
      item.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
      item.Arrange(new Rect(item.DesiredSize));
    

    In this example the MenuItem has not been given an explicit height or width. However, forcing the render will render it taking the supplied header text and icon into consideration.

    0 讨论(0)
提交回复
热议问题