开发者

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(开发者_Go百科))
    {
        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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜