问题
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);
}
回答1:
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();
来源:https://stackoverflow.com/questions/19631680/rendering-a-usercontrol-in-code-rather-than-xaml