简体   繁体   中英

RenderTargetBitmap problem

I am trying to add the image of a usercontrol to viewbox. I am creating the usercontrol dynamically. I am using the code below.

private static RenderTargetBitmap CaptureScreen(Visual target, double dpiX, double dpiY)
{
    if (target == null)
    {
        return null;
    }
    Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
    //RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
    //                                                (int)(bounds.Height * dpiY / 96.0),
    //                                                dpiX,
    //                                                dpiY,
    //                                                PixelFormats.Pbgra32);
    RenderTargetBitmap rtb = new RenderTargetBitmap(596,596,dpiX,
                                                    dpiY,
                                                    PixelFormats.Pbgra32);
    DrawingVisual dv = new DrawingVisual();
    using (DrawingContext ctx = dv.RenderOpen())
    {
        VisualBrush vb = new VisualBrush(target);
        ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
    }
    rtb.Render(dv);
    return rtb;
}

I am creating the user control dynamically and passing this to capture screen method.

UserControls.UserControl1 uc1 = new UserControls.UserControl1();
                        visualList.Add(uc1);
 for(int i = 0;i<=6;i++)
        {
            Image img = new Image();
            img.Source = CaptureScreen(visualList[i], 96, 96);
            img.Margin = new Thickness { Top = 2 };                   
            usingWorkaround.Children.Add(img);
        }

the VisualTreeHelper.GetDescendantBounds(target) is returning empty bounds. Thats why the image of the screen can not be created. Is there any other method to capture screen of dynamically created user control?

you can call Measure and Arrange As follows

  private void ForceUpdate(FrameworkElement element, double width, double height)
  {
     Size size = new Size(width, height);

     element.Measure(size);

     element.Arrange(new Rect(0, 0, width, height));

     element.UpdateLayout();
  }

At the time when you try to create the image the controls don't yet exist in the visual tree and the size has not been calculated.

You will need to call Measure and Arrange on your visual first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM