我有一个PictureBox控件。当我单击控件上的图像时,事件处理程序被触发。
这是事件处理程序:
Private Sub pbImageHolder_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles pbImageHolder.Click
Dim clickPoint As Point = MousePosition
Dim img As Bitmap = New Bitmap(pbImageHolder.Image)
pixelColor = img.GetPixel(clickPoint.X, clickPoint.Y)
For i As Integer = 0 To img.Width
For j As Integer = 0 To img.Height
Next
Next
End Sub
问题是我进入了这一行:
pixelColor = img.GetPixel(clickPoint.X, clickPoint.Y)
这是一个例外:
System.ArgumentOutOfRangeException未处理
消息=参数必须为正且<宽度。参数名称:x
PARAMNAME = X
源= System.Drawing中
知道如何修复代码?
答案 0 :(得分:1)
假设SizeMode是默认的Normal(请参阅下面的Hans评论),MouseClick事件将是一个更合适的事件来处理而不是点击,因为它会为你传递鼠标位置。
此外,您需要检查该点是否在图像的范围内。
Private Sub pbImageHolder_MouseClick(ByVal sender As Object, _
ByVal e As MouseEventArgs) _
Handles pbImageHolder.MouseClick
Using img As Bitmap = New Bitmap(pbImageHolder.Image)
If New Rectangle(Point.Empty, img.Size).Contains(e.Location) Then
pixelColor = img.GetPixel(e.Location.X, e.Location.Y)
For i As Integer = 0 To img.Width - 1
For j As Integer = 0 To img.Height - 1
Next
Next
End If
End Using
End Sub
对于循环,请确保小于宽度和高度。
除非您不知道范围,否则您不应该为此错误尝试Try-Catch,但在这种情况下,您知道范围与图像的大小有关。