【问题标题】:C# Saving panel image gives different resultsC# 保存面板图像给出不同的结果
【发布时间】:2015-10-28 17:55:55
【问题描述】:

以下是将面板信息更改为位图的代码。 位图首先由我的面板信息生成,然后保存为图像文件。 我确认宽度、高度和边界代表了我的面板给出的正确信息。 我目前不确定为什么我的结果 bmp/jpeg 文件与面板上的图像不同。

//位图保存功能

        Bitmap bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
        Debug.WriteLine("bounds: " + panel1.ClientRectangle);
        this.panel1.DrawToBitmap(bmp, panel1.ClientRectangle);
        bmp.Save(@"C:\Documents and Settings\Flaw\Desktop\Test.bmp", ImageFormat.Bmp);

//绘图函数

        System.Drawing.Graphics graphicsObj;

        graphicsObj = this.panel1.CreateGraphics();

        Pen myPen = new Pen(System.Drawing.Color.Black, 5);
        graphicsObj.Clear(Color.White);
        //graphicsObj.DrawLine(myPen, 50, 50, 100, 100);
        if (bCircle)
        {
            graphicsObj.DrawEllipse(myPen, x, y, 100, 100);
        }
        else if (bSquare)
        {
            graphicsObj.DrawRectangle(myPen, x, y, 100, 100);
        }

我保存位图得到的结果。

panel1 上的图像(从我的窗口窗体中裁剪)

【问题讨论】:

    标签: c#


    【解决方案1】:

    您的 Bounds 属性是面板与父容器的关系,因此这并不总是有效:

    this.panel1.DrawToBitmap(bmp, panel1.Bounds);
    

    试试这个:

    this.panel1.DrawToBitmap(bmp, panel1.ClientRectangle);
    

    您的位图大小也应该使用 ClientSize 属性,因为面板的 Width 和 Height 属性包括任何边框大小:

    Bitmap bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height);
    

    根据您的更新,CreateGraphics 是一个临时画布,不会成为面板的一部分,因此没有可保存的内容。改用面板的绘制事件:

    private void panel1_Paint(object sender, PaintEventArgs e) {
      using (Pen myPen = new Pen(Color.Black, 5)) {
        e.Graphics.Clear(Color.White);
        if (bCircle) {
          e.Graphics.DrawEllipse(myPen, x, y, 100, 100);
        } else if (bSquare) {
          e.Graphics.DrawRectangle(myPen, x, y, 100, 100);
        }
      }
    }
    

    要进行更新,您只需使控件无效:

    panel1.Invalidate();
    

    【讨论】:

    • 我将代码更新为:Bitmap bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height); Debug.WriteLine("边界:" + panel1.ClientRectangle); this.panel1.DrawToBitmap(bmp, panel1.ClientRectangle); bmp.Save(@"C:\Documents and Settings\Flaw\Desktop\Test.bmp", ImageFormat.Bmp);但现在结果是与窗口窗体颜色相同的纯灰色。
    • @user3235731 我不知道您的面板中有什么。你需要记录下来。
    • @user3235731 您对帖子的编辑没有帮助。你是在面板上画画吗?他们的控件在面板中吗?那个面板是怎么得到黑色边框的?
    • 这有点猜不透。告诉他先最小化并恢复窗口:)
    • @HansPassant CreateGraphics,通常的嫌疑人。
    猜你喜欢
    • 2020-08-21
    • 1970-01-01
    • 2019-04-03
    • 2012-05-07
    • 2018-08-30
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多