2017-08-06 52 views
0

我正在嘗試通過更改圖片框的填充使用鼠標在圖片框內移動圖片。我能夠移動圖像,但它moves too much。這是我走到這一步:如何使用填充在C#中的圖片框內移動圖像?

private bool mouseDown; 
private Point lastLocation; 

private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
     mouseDown = true; 
     lastLocation = e.Location; 
    } 
} 

private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
{ 
    if (mouseDown == true) 
    { 
     int dx = e.X - lastLocation.X; 
     int dy = e.Y - lastLocation.Y; 
     pictureBox1.Padding = new Padding(pictureBox1.Padding.Left + dx, 
            pictureBox1.Padding.Top + dy, 0, 0); 
     pictureBox1.Invalidate(); 
    } 
} 

private void pictureBox1_MouseUp(object sender, MouseEventArgs e) 
{ 
    mouseDown = false; 
} 

回答

1

的幫助,我找到了一個解決方案:

下的MouseMove,我換成

pictureBox1.Padding = new Padding(pictureBox1.Padding.Left + dx, 
           pictureBox1.Padding.Top + dy, 0, 0); 

pictureBox1.Padding = new Padding(Padding.Left + dx, Padding.Top + dy, 0, 0); 
0

我想這是因爲你添加更多的填充時,參照當前填充每次加更多的填充:

pictureBox1.Padding = new Padding(pictureBox1.Padding.Left + dx, 
           pictureBox1.Padding.Top + dy, 0, 0); 

嘗試,而不是:

pictureBox1.Padding = new Padding(dx, dy, 0, 0); 
+0

謝謝。但是,現在它在我第一次移動它時正確移動,但是在移動之前圖像第二次跳回到之前的位置。 – Xrio