2013-06-04 38 views
1

我想要的图像绘制到一个图片(pbImage)并将其转换成后位,但它崩溃,因为pcImage.Image是apperently null,我可以看到图纸崩溃,所以我不明白是怎么回事null之前。转换时c#崩溃,显然为空?

以下是错误:

An unhandled exception of type 'System.NullReferenceException' occurred in System.Drawing.dll Additional information: Object reference not set to an instance of an object.

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 
+0

我的猜测是'pbImage.Image'为空。无论如何,我们不是在这里调试你的代码,你有没有试过找到你在20秒内完成的原因,这就是为什么我低估了这个问题。 – gdoron

+2

'pbImage.Image'从未在此代码中设置...因此它可能为空... – emd

+0

尝试在创建图形前查看'pbImage.Image'并查看它是否为空 – BrunoLM

回答

5

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

是的,因为您绘制的图片到SCREEN有:

Graphics G = Graphics.FromHwnd(pbImage.Handle); 

这简直是“上面”的图片框绘制到临时图形。如果你通过另一个窗口,任何以这种方式绘制的东西都会被删除。实际上没有分配给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; 
+0

你先生是老板! – user2452478

0

我不能肯定,但我认为你需要释放Graphics对象使用图片前。试试这个...

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