C#以编程方式呈现面板

时间:2017-08-30 16:28:35

标签: c# winforms

我有一个类MyUserControl,其中包含一些通常我添加到表单中进行可视化的图表。

但是,我有一项功能要求我将MyUserControl对象写入图像文件,但我似乎只在图像中看到白色。

我的代码如下:

MyUserControl uc = new MyUserControl();
uc.loadData();
int width = uc.Size.Width;
int height = uc.Size.Height;
Bitmap bm = new Bitmap(width, height);
uc.DrawToBitmap(bm, new Rectangle(0, 0, width, height));
bm.Save(@"C:\path\to\file.bmp");

我需要做什么来“欺骗”我的MyUserControl认为它已经被添加到面板中进行渲染,但是将它直接渲染到文件中呢?

1 个答案:

答案 0 :(得分:0)

您可以向控件添加SaveToBitmap()方法。因此,您可以调用受保护的OnPaint()方法。

public class MyUserControl : UserControl
{
   ...
  public void SaveToBitmap(string filePath)
  {
    using(Graphics g = this.CreateGraphics())
    {
      var bmp = new Bitmap(this.ClientSize.Width, this.ClientSize.Height, g);
      using(Graphics gBmp = Graphics.FromImage(bmp))
      {
        PaintEventArgs e = new PaintEventArgs(gBmp, this.ClientRectangle);
        this.OnPaint(e);        
      }
      bmp.Save(filePath);        
    }
  }
}