在代码而不是XAML中呈现UserControl

时间:2013-10-28 09:55:25

标签: c# wpf xaml user-controls rendertargetbitmap

我想使用RenderTargetBitmap将UserControl呈现给位图,而不必为其编写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);
}

1 个答案:

答案 0 :(得分:3)

而不是UpdateLayout,您必须致电MeasureArrange以完成布局:

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

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