您当前的位置:首页 > 文章 > C# 自定义控件GDI绘制在主程序报错

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

作者:魔豆1 时间:2023-06-27 阅读数:263 人阅读
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)
    {
    
    }
}

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

原文链接:https://blog.csdn.net/qq996980215/article/details/107559799

本站大部分文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了您的权益请来信告知我们删除。邮箱:1451803763@qq.com