在代码中而不是 XAML 中呈现 UserControl而不是、代码、UserControl、XAML

2023-09-07 15:33:20 作者:我、独一无二

我想使用 RenderTargetBitmap 将 UserControl 呈现为位图,而无需为其编写 XAML.当我这样做时,我得到一个空白图像,我是否错过了关键步骤?

I want to use RenderTargetBitmap to render a UserControl to a bitmap without having to write the XAML for it. When I do this I get a blank image, am I missing a crucial step?

ValTool.Controls.VideoFisheyeOverlayControl vfoc = new Controls.VideoFisheyeOverlayControl();
vfoc.Width = (int)this.VideoContainer.ActualWidth;
vfoc.Height = (int)this.VideoContainer.ActualHeight;
vfoc.FieldsOfView=this.FieldsOfView;
vfoc.CountLines = this.CountLines;

vfoc.UpdateLayout();
vfoc.InvalidateVisual();

RenderTargetBitmap visual = new RenderTargetBitmap((int)this.VideoContainer.ActualWidth, (int)this.VideoContainer.ActualHeight, 96, 96, PixelFormats.Pbgra32);
visual.Render(vfoc);
var finalImage = BitmapFrame.Create(visual);
// Encoding the RenderBitmapTarget as a PNG file.
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(finalImage));
using (Stream stm = File.Create(@"new.png"))
{
    png.Save(stm);
}

推荐答案

您必须调用 测量和 安排 完成布局:

Instead of UpdateLayout you have to call Measure and Arrange to get the layout done:

var width = VideoContainer.ActualWidth;
var height = VideoContainer.ActualHeight;

vfoc.Measure(new Size(width, height));
vfoc.Arrange(new Rect(0, 0, width, height));
vfoc.InvalidateVisual();