在代码而不是 XAML 中呈现用户控件

本文关键字:用户 控件 XAML 代码 | 更新日期: 2023-09-27 18:37:17

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

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);
}

在代码而不是 XAML 中呈现用户控件

而不是UpdateLayout,你必须调用Measure and Ranges来完成布局:

var width = VideoContainer.ActualWidth;
var height = VideoContainer.ActualHeight;
vfoc.Measure(new Size(width, height));
vfoc.Arrange(new Rect(0, 0, width, height));
vfoc.InvalidateVisual();