How to render a WPF UserControl to a bitmap without creating a window

后端 未结 4 969
梦谈多话
梦谈多话 2020-11-27 04:27

How can I render a WPF UserControl to a bitmap without creating a window? I need to render a WPF UserControl and upload it to another program. The bitmaps will be rendered t

4条回答
  •  感动是毒
    2020-11-27 04:51

    Have you tried spinning up an instance of the user control and doing something like this:

    UserControl control = new UserControl1();
    
    control.Measure(new Size(300, 300));
    control.Arrange(new Rect(new Size(300,300)));
    
    RenderTargetBitmap bmp = new RenderTargetBitmap(300, 300, 96, 96, PixelFormats.Pbgra32);
    
    bmp.Render(control);
    
    var encoder = new PngBitmapEncoder();
    
    encoder.Frames.Add(BitmapFrame.Create(bmp));
    
    using (Stream stm = File.Create(@"c:\test.png"))
       encoder.Save(stm);
    

    It looks like you need to Measure, Arrange. This worked for me.

提交回复
热议问题