简体   繁体   English

RenderTargetBitmap问题

[英]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. VisualTreeHelper.GetDescendantBounds(target)返回空边界。 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. 您首先需要在视觉上调用“ 测量排列 ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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