C#System.ArgumentException

2 篇文章 0 订阅
2 篇文章 0 订阅

C#自定义控件GDI绘制在主程序报错System.ArgumentException;

我的绘制图片内容大概如下:

private Bitmap backGroundImage=null;
private Bitmap prospectImage=null;
private Graphics graphics = null;
/// <summary>
/// 在背景上画前景
/// </summary>
private void drawProspect()
{
    try
    {
        if(prospectImage!=null)  //注释
            prospectImage.Dispose();  //注释
        prospectImage = backGroundImage.Clone() as Bitmap;

        using (graphics = Graphics.FromImage(prospectImage))
        {
            //画你所需要的内容
        }
        pictrueBox1.Image=prospectImage;
    }catch(Exception ee)
    {
    
    }
}

在线程高速(50ms以下一次)运行下就会随机报这个错 :

System.ArgumentException: 参数无效。.

   在 System.Drawing.Image.get_Width()
   在 System.Drawing.Image.get_Size()
   在 System.Windows.Forms.PictureBox.ImageRectangleFromSizeMode(PictureBoxSizeMode mode)
   在 System.Windows.Forms.PictureBox.get_ImageRectangle()
   在 System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
   在 System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
   在 System.Windows.Forms.Control.WmPaint(Message& m)
   在 System.Windows.Forms.Control.WndProc(Message& m)
   在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

这种错误连错在哪在代码哪一行都不知道,连try也无法捕捉到。

经过各种尝试,发现我不写释放prospectImage那两行代码时,就不会报这个错(就是上面代码中有注释的两行代码)。

但是这样的话,内存就会疯涨,不合理。于是就有了下面的解决方法:

private Bitmap backGroundImage=null;
private Bitmap prospectImage=null;
private Image prospectImageCpoy = null;
private Graphics graphics = null;
/// <summary>
/// 在背景上画前景
/// </summary>
private void drawProspect()
{
    try
    {
        //if(prospectImage!=null)  //注释
        //   prospectImage.Dispose();  //注释
        prospectImage = backGroundImage.Clone() as Bitmap;

        using (graphics = Graphics.FromImage(prospectImage))
        {
            //画你所需要的内容
        }
       prospectImageCpoy = pictureBox1.Image;//保存上一次的图片
       pictureBox1.Image = prospectImage;//覆盖上一次的图片
       prospectImageCpoy.Dispose();//释放上一次的图片
    }catch(Exception ee)
    {
    
    }
}

内存不再疯涨了,运行也稳定了,完美解决。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值