panel1.DrawToBitmap不从DrawLine绘制线条

时间:2013-05-09 14:22:12

标签: c# visual-studio jpeg system.drawing drawtobitmap

我有一个面板,我正在使用它绘制线条:

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没有保存正在绘制的线条。

1 个答案:

答案 0 :(得分:0)

所以我做了一个解决核心问题的解决方法。我制作了一系列绘制线条的点,然后我做了这个:

        // 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);
        }
    }