Visual Studio 2017中DrawArc抛出System.ArgumentException问题求助
四冲程循环仿真程序System.ArgumentException异常排查与解决
我正在开发四冲程循环仿真程序,在Visual Studio 2017中调试时触发了System.ArgumentException异常,不知如何解决。
相关代码(已替换$exception为Mygraphics)
Private Sub Animation(q2) Dim MyGraphics As Graphics MyGraphics = Me.CreateGraphics Dim Mycolor As Color = Color.FromArgb(0, 255, 0) Dim MyPen As New Pen(Color.Green, 1) Dim ox, oy, ax, ay, bx, by, crank_length, conrod_length Dim k Dim q, r As Integer MyGraphics.Clear(Color.WhiteSmoke) Call position_analysis(q2) k = 800 crank_length = r2 * k conrod_length = r3 * k '------------------ ox = 150 oy = 300 ax = ox + crank_length * Math.Cos(q2) ay = oy - crank_length * Math.Sin(q2) bx = ax + conrod_length * Math.Cos(q3) by = oy '------------------ r = crank_length q = q2 * 180 / pi If q > 360 Then q = q - 360 q = 360 - q MyGraphics.DrawArc(MyPen, ox - r, oy - r, 2 * r, 2 * r, q, 90) '------------------- LineShape1.X1 = ox LineShape1.Y1 = oy LineShape1.X2 = ox + crank_length + conrod_length + 100 LineShape1.Y2 = oy LineShape2.X1 = ox LineShape2.Y1 = ox LineShape2.X2 = ax LineShape2.Y2 = ay LineShape3.X1 = ax LineShape3.Y1 = ay LineShape3.X2 = bx LineShape3.Y2 = by OvalShape1.Location = New Point(ox - OvalShape1.Width / 2, oy - OvalShape1.Height / 2) OvalShape2.Location = New Point(ax - OvalShape2.Width / 2, ay - OvalShape2.Height / 2) OvalShape3.Location = New Point(bx - OvalShape3.Width / 2, by - OvalShape3.Height / 2) RectangleShape1.Location = New Point(bx - RectangleShape1.Width / 2, by - RectangleShape1.Height / 2) End Sub
异常相关截图信息
- 截图1:调试时触发System.ArgumentException,提示“参数无效”,异常指向
MyGraphics.DrawArc代码行 - 截图2:显示异常的详细调用栈,确认异常源自GDI+绘图操作的参数错误
问题排查与解决步骤
核心问题分析
System.ArgumentException在DrawArc触发,通常是因为参数不符合GDI+要求:
- 绘图矩形的宽度/高度(第4、5个参数)为非正数
- 角度参数超出合法范围或类型不匹配
- 变量未正确初始化导致数值异常
具体修复措施
明确变量类型,避免Variant隐患:
原代码大量变量未声明类型,默认是Variant,容易引发类型转换错误。修改变量声明:Dim ox As Integer, oy As Integer, ax As Double, ay As Double, bx As Double, by As Integer Dim crank_length As Double, conrod_length As Double Dim k As Integer = 800 Dim q As Single, r As Integer修复
LineShape2的坐标错误:
原代码LineShape2.Y1 = ox是明显错误,应该改为oy,否则控件位置异常可能间接引发问题:LineShape2.Y1 = oy确保
DrawArc参数合法:- 检查
r2、r3在position_analysis(q2)执行后是否被赋值为正数,否则crank_length会为非正数,导致2*r无效 - 将角度变量
q改为Single类型(匹配DrawArc的参数要求),避免整数转换丢失精度:q = CSng(q2 * 180 / Math.PI) - 添加参数合法性判断,避免无效绘图:
If r > 0 Then MyGraphics.DrawArc(MyPen, ox - r, oy - r, 2 * r, 2 * r, q, 90) End If
- 检查
优化GDI资源管理:
使用Using语句自动释放Pen资源,避免内存泄漏:Using MyPen As New Pen(Color.Green, 1) MyGraphics.DrawArc(MyPen, ox - r, oy - r, 2 * r, 2 * r, q, 90) ' 其他使用MyPen的绘图操作也放在这里 End Using验证
MyGraphics对象有效性:
添加非空判断,避免空引用异常:If MyGraphics IsNot Nothing Then MyGraphics.Clear(Color.WhiteSmoke) ' 后续绘图操作 End If
内容的提问来源于stack exchange,提问作者IJH
相关产品推荐
相关产品推荐

