c#转换时崩溃,显然是null

本文关键字:null 转换 崩溃 | 更新日期: 2023-09-27 18:16:57

我试图绘制图像到一个图片框(pbImage),并将其转换为位图后,但它崩溃了,因为pcImage.Image显然是null,我可以在它崩溃之前看到绘图,所以我不明白它是如何null的。

错误如下:

类型为"System"的未处理异常。附加信息:对象引用未设置为对象的实例。

bool[,] bCollision = new bool[pbImage.Width,pbImage.Height];
Color cPixelCol;
Graphics G = Graphics.FromHwnd(pbImage.Handle);
Pen SquarePen = new Pen(Color.Black, 5);
SquarePen = new Pen(Color.Red, 5);
Brush BackBrush = new SolidBrush(Color.Aqua);
G.FillRectangle(BackBrush, 50, 50, this.Width, this.Height);
G.DrawLine(SquarePen, 410, 50, 410, 400);
G.DrawEllipse(SquarePen, 50 + x, 50, 100+x, 50);
Bitmap bm = new Bitmap(pbImage.Image);   <------------- this line crashes

c#转换时崩溃,显然是null

"我可以在崩溃之前看到绘图,所以我不明白它是如何为空的。"

是的,因为您使用

将图像绘制到屏幕
Graphics G = Graphics.FromHwnd(pbImage.Handle);

这只是将"在顶部"的PictureBox绘制到临时图形。任何以这种方式绘制的东西,如果你通过另一个窗口,就会被擦除。实际上并没有给PictureBox的Image()属性赋值。

为什么不从创建位图开始,然后从中获得图形?然后你可以把这个位图分配给你的PictureBox:

        Bitmap bmp = new Bitmap(pbImage.Width, pbImage.Height); // not sure what widht/height you really need
        using (Graphics G = Graphics.FromImage(bmp))
        {
            using (Pen SquarePen = new Pen(Color.Red, 5))
            {
                G.Clear(Color.Aqua);
                G.DrawLine(SquarePen, 410, 50, 410, 400);
                G.DrawEllipse(SquarePen, 50 + x, 50, 100 + x, 50);
            }
        }
        pbImage.Image = bmp;

我不确定,但我认为在使用Image之前需要释放Graphics对象。试试这个…

G.DrawEllipse(SquarePen, 50 + x, 50, 100+x, 50);
G.Dispose();
Bitmap bm = new Bitmap(pbImage.Image);