2

我的图像在面板内,我为边界设置了一个 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
4

1 回答 1

1

首先,如果您将 PictureBox放在Panel 中,那么您不需要考虑 Panel 的位置,因为 PictureBox 的位置将在 Panel 的左上角归零。

这个条件:

If PictureBox.Location.X <= Panel1.Location.X ...

应改为这种情况:

If PictureBox.Location.X <= 0


此外,您遇到的问题是由于您的事件处理程序在将 PictureBox 从 0,0 移动到将 PictureBox 移动到增量位置之间翻转。

例如:
当您将 PictureBox 向右拖动以使其左边界越过面板的左边界(即 PictureBox.Location.X > 0)时,您的 if 语句的条件评估为 False,并且 PictureBox 的位置设置为 0 . 但是,由于您现在更改了它的位置,因此再次触发 MouseMove 事件,这一次您的 if 语句的条件为 True,并且 PictureBox 的位置设置为增量位置。再次触发 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
于 2011-07-04T01:49:30.943 回答