【问题标题】:C# Graphics shown in Form but not in BitmapC# 图形显示在表单中但不在位图中
【发布时间】:2012-11-29 10:10:58
【问题描述】:

我正在使用 C#,我想在 Form 上绘制一些多边形,然后将图形保存在 Bitmap 中。

按照this question 的回答,我在 Form 类中编写了一个方法:

  private void draw_pol()
  {
      Graphics d = this.CreateGraphics();

      // drawing stuff

      Bitmap bmp = new Bitmap(this.Width, this.Height, d);
      bmp.Save("image.bmp");
  }

通过这种方式,表单正确显示图形并创建名为“image.bmp”的位图文件,但该文件是白色图像。

为什么 bmp 文件没有显示任何图像?我做错了什么?

非常感谢。

【问题讨论】:

    标签: c# graphics bitmap


    【解决方案1】:

    您传递给位图的图形参数仅用于指定位图的分辨率。它不会以任何方式绘制位图。

    来自MSDN

    此方法创建的新位图分别从 g 的 DpiX 和 DpiY 属性获取其水平和垂直分辨率。

    改为使用Graphics.FromImage() 来获取您可以使用的Graphics 对象。此外,您应该在绘画后DisposeGraphics 对象。这是using 语句的理想用法。

    Bitmap bmp = new Bitmap(this.Width, this.Height);
    using (Graphics g = Graphics.FromImage(bmp))
    {
        //paint stuff
    }
    bmp.Save(yourFile);
    

    如果您还需要将其绘制到表单上,您可以轻松地绘制您创建的位图:

    Graphics g = this.CreateGraphics();
    g.DrawImage(bmp, 0, 0);
    

    【讨论】:

    • 非常感谢!这正是我想要的!
    【解决方案2】:

    Graphics 实例仅在一个 Bitmap 上运行。它要么是您要保存的那个,要么是您表单上的那个。

    例如,您可以这样做以在表单上渲染绘制的位图并在之后保存:

    private void DrawOnBitmap()
    {
        using (var bitmap = new Bitmap(this.Width, this.Height))
        {
            using (var bitmapGraphics = Graphics.FromImage(bitmap))
            {
                // Draw on the bitmap
                var pen = new Pen(Color.Red);
                var rect = new Rectangle(20, 20, 100, 100);
                bitmapGraphics.DrawRectangle(pen, rect);
    
                // Display the bitmap on the form
                using (var formGraphics = this.CreateGraphics())
                {
                    formGraphics.DrawImage(bitmap, new Point(0, 0));
                }
    
                // Save the bitmap
                bitmap.Save("image.bmp");
            }
        }
    }   
    

    【讨论】:

      【解决方案3】:

      您需要一个表示位图的图形对象,以便您可以在图像上绘图。这样做:

      • 创建位图对象
      • 使用 Graphics.FromImage 方法创建图形对象
      • 将位图对象作为参数传递给图形对象

        Bitmap bmp = new Bitmap(this.Width, this.Height, d);
                  bmp.Save("image.bmp");//for your need
             Graphics d=Graphics.FromImage(bmp);
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-28
        • 1970-01-01
        • 1970-01-01
        • 2015-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多