代码之家  ›  专栏  ›  技术社区  ›  TerribleDog

将所有绘制的对象保存到位图中

  •  1
  • TerribleDog  · 技术社区  · 7 年前

    位图文件 . 我不知道该怎么开始?

    enter image description here

    PS:我使用不同的图形对象来绘制每个。

    2 回复  |  直到 7 年前
        1
  •  3
  •   TerribleDog    7 年前

    找到解决方法,这将在我的pictureBox/Canvas中保存图形。

    private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog save = new SaveFileDialog();
    
                //Creates a filter fir saving the Project File
                save.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp); *.PNG|*.jpg; *.jpeg; *.gif; *.bmp; *.PNG";     
                save.DefaultExt = ".bmp";
                save.AddExtension = true;
    
                if (save.ShowDialog() == DialogResult.OK)
                {
                    using (var bmp = new Bitmap(pictureBox_Canvass.Width, pictureBox_Canvass.Height))
                    {
                        pictureBox_Canvass.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
                        bmp.Save(save.FileName);
                    }
                }
        }
    

    enter image description here

        2
  •  1
  •   Barmak Shemirani    7 年前

    Graphics 是一个 "device context" 对象它将图形处理到计算机上 Bitmap ,但无法将其转换回 位图 .

    然而,你可以复制已经画在你的窗户上的部分,然后画在你的窗户上 绘图

    protected override void OnMouseClick(MouseEventArgs e)
    {
        base.OnMouseClick(e);
    
        //get the screen coordinates for this window
        var rect = this.RectangleToScreen(this.ClientRectangle);
    
        //copy bits from screen to bitmap
        using (var bmp = new Bitmap(rect.Width, rect.Height))
        {
            var gr = Graphics.FromImage(bmp);
            gr.CopyFromScreen(rect.Left, rect.Top, 0, 0, rect.Size);
    
            //save to file
            bmp.Save(@"c:\test\test.bmp");
        }
    }
    

    或者,您可以在响应Windows消息绘制后立即执行此操作,但您必须调用 Graphics::Flush 当您完成绘制时,让Windows知道。此方法假定目标窗口可见。命令之间可能存在延迟,或者部分窗口不可见,并且无法获得所需的输出。

    在另一个答案中建议了一个更好的解决方案:创建一个内存位图并利用它。

    public void do_all_paintings(Graphics gr)
    {
        //paint something random, add all other drawings
        gr.Clear(Color.Red);
    }
    

    现在绘制以响应Windows绘制请求:

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        do_all_paintings(e.Graphics);
    }
    

    使用相同的 do_all_paintings 函数创建文件以响应命令:

    protected override void OnMouseClick(MouseEventArgs e)
    {
        base.OnMouseClick(e);
    
        var rect = this.RectangleToScreen(this.ClientRectangle);
        using (var bmp = new Bitmap(rect.Width, rect.Height))
        {
            do_all_paintings(Graphics.FromImage(bmp));
            bmp.Save(@"c:\test\test.bmp");
        }
    }