panel1.DrawToBitmap不会从DrawLine中绘制线条

本文关键字:绘制 DrawLine DrawToBitmap panel1 | 更新日期: 2023-09-27 18:12:46

我有一个面板,我正在使用:

Point PreviousPoint = new Point (0,0);
Point NewPoint = new Point (10,10);
Pen MyPen = new Pen(Color.Black, 2);
Graphics MyGraphics = panel1.CreateGraphics();
MyGraphics.DrawLine(MyPen, PreviousPoint, NewPoint);

这一切都很好。我显然改变了点来画更多的线,但这对这个问题没有影响。我想把面板导出为jpg文件。我使用以下代码:

Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, panel1.Width, panel1.Height));
bmp.Save("C:''panel.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

输出一个空白的jpg。我的面板的背景是灰色的,jpg的背景也是同样的灰色,所以我知道它实际上是在导出面板。此外,我在面板中添加了一个按钮,只是为了看看它是否会被保存,它确实保存了。所以由于某些原因,jpg没有保存正在绘制的线条

panel1.DrawToBitmap不会从DrawLine中绘制线条

所以我做了一个解决核心问题的变通方法。我绘制了一个用于绘制线条的点的数组,然后我这样做:

        // make sure you actually drew something
        if (MyLines.Length > 0)
        {
            // instantiate the stuff you need
            Image img = new Bitmap(panel1.Width, panel1.Height);
            Graphics g = Graphics.FromImage(img);
            Pen pen = new Pen(Color.Black, 2);
            // draw every line (from every even index to the one after it)
            for (int i = 0; i < MyLines.Length; i++)
            {
                if (i % 2 == 0)
                {
                    g.DrawLine(pen, MyLines[i], MyLines[i + 1]);
                }
            }
            img.Save("C:''panel.png", System.Drawing.Imaging.ImageFormat.Png);
        }
    }