2011-07-02 60 views
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 

回答

1

首先,如果你有你的PictureBox 你的面板裏面,那麼你就需要考慮小組的位置,因爲圖片框的位置將是置於專家組左上方。

這種情況:

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

應該改變這種狀況:

If PictureBox.Location.X <= 0 


此外,你運行到這個問題是由於這一事實,您的活動處理程序正在將PictureBox從0,0移動到將PictureBox移動到三角洲位置之間。

如:
當你拖動圖片框向右,使得它的左邊界去通過小組的左邊界(即PictureBox.Location.X> 0),那麼你的if語句的條件計算爲false和PictureBox的位置設置爲0.但是,由於您現在已更改其位置,因此再次觸發MouseMove事件,並且此時if語句的條件評估爲True,並且PictureBox的位置設置爲增量位置。 再次觸發MouseMove事件並重復場景,來回翻轉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 
+0

感謝的人!它真的幫助:)。 – jko