我的图像在面板内部,我为边界设置了一个if语句,只能移动它。当我试图运行它时,当鼠标将其平移到边界外时,它看起来很糟糕。这是我的平移代码:
If (mouse.Button = Windows.Forms.MouseButtons.Left) Then
Dim mousePosNow As Point = mouse.Location
Dim deltaX As Integer = mousePosNow.X - mouseDowns.X
Dim deltaY As Integer = mousePosNow.Y - mouseDowns.Y
Dim newX As Integer
Dim newY As Integer
If PictureBox1.Location.X <= Panel1.Location.X And PictureBox1.Location.Y <= Panel1.Location.Y And _
(PictureBox1.Location.X + PictureBox1.Width) >= (Panel1.Location.X + Panel1.Width) And _
(PictureBox1.Location.Y + PictureBox1.Height) >= (Panel1.Location.Y + Panel1.Height) Then
newX = PictureBox1.Location.X + deltaX
newY = PictureBox1.Location.Y + deltaY
End If
PictureBox1.Location = New Point(newX, newY)
End If
答案 0 :(得分:1)
首先,如果您的Panel中有PictureBox ,那么您不需要考虑Panel的位置,因为PictureBox的位置将在左上角归零小组。
这个条件:
If PictureBox.Location.X <= Panel1.Location.X ...
应该改为这个条件:
If PictureBox.Location.X <= 0
此外,您遇到的问题是由于您的事件处理程序在将PictureBox从0,0移动到将PictureBox移动到增量位置之间翻转的事实。
例如:
当您向右拖动PictureBox使其左边界经过Panel的左边界(即PictureBox.Location.X> 0)时,if语句的条件评估为False,PictureBox的位置设置为0。但是,由于您现在已经更改了它的位置,因此再次触发MouseMove事件,这次if语句的条件评估为True,PictureBox的位置设置为delta位置。
再次触发MouseMove事件并重复该场景,来回翻转PictureBox的位置,从而产生抖动效果。
您可以通过更改条件来依赖PictureBox的新位置而不是当前位置来解决此问题:
这个条件:
If PictureBox.Location.X <= 0 ...
应该改为这个条件:
If (PictureBox.Location.X + deltaX) <= 0 ...
这解决了抖动问题,但您的代码只处理将PictureBox向右和向下拖动的情况。
不是编写更多条件,而是通过将计算移动到单独处理每个轴的单独函数中来简化代码:
If (mouse.Button = Windows.Forms.MouseButtons.Left) Then
Dim mousePosNow As Point = mouse.Location
Dim deltaX As Integer = mousePosNow.X - mouseDowns.X
Dim deltaY As Integer = mousePosNow.Y - mouseDowns.Y
Dim newX As Integer = Clamp(PictureBox1.Location.X + deltaX, PictureBox1.Width, Panel1.Width)
Dim newY As Integer = Clamp(PictureBox1.Location.Y + deltaY, PictureBox1.Height, Panel1.Height)
PictureBox1.Location = New Point(newX, newY)
End If
...
Private Function Clamp(val As Integer, outerBound As Integer, innerBound As Integer) As Integer
Dim newVal As Integer = val
If newVal > 0 Then
newVal = 0
End If
If newVal + outerBound < innerBound Then
newVal = innerBound - outerBound
End If
Return newVal
End Function