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がある場合は、パネルの左上で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の場所がデルタの場所に設定されます。もう一度、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 に答える