【问题标题】:Picturebox Panning Boundary inside Panel面板内的 Picturebox 平移边界
【发布时间】:2011-09-27 08:55:52
【问题描述】:

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

【问题讨论】:

    标签: vb.net winforms panel picturebox boundary


    【解决方案1】:

    首先,如果您将 PictureBox 放在 Panel 中,则无需考虑 Panel 的位置,因为 PictureBox 的位置将在左上角归零小组成员。

    这个条件:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 2020-02-06
      相关资源
      最近更新 更多