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

Rendering a UserControl in code rather than XAML(在代码中而不是 XAML 中呈现 UserControl)

本文介绍了在代码中而不是 XAML 中呈现 UserControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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();

这篇关于在代码中而不是 XAML 中呈现 UserControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在代码中而不是 XAML 中呈现 UserControl