简体   繁体   English

C#WinForm中不寻常的拖动问题

[英]Unusual dragging issue in C# WinForm

I've got a PictureBox which can be dragged by the user. 我有一个可以被用户拖动的PictureBox。 When the dragging is done, the component appears to move continuously from side to side, like vibrating. 拖动完成后,组件似乎从一侧到另一侧连续移动,就像振动一样。

Your code is not very logical. 你的代码不合逻辑。 It says: If the user drags the note one pixel downwards, the note is set one step down. 它说:如果用户将音符向下拖动一个像素,则音符设置为向下一步。 If the mouse then is moved sidewards, the note moves down a step for every pixel the mouse is moved. 如果鼠标然后向侧面移动,则对于鼠标移动的每个像素,笔记向下移动一步。

I'd suggest to go back to concept. 我建议回到概念。

  • At first, the mouse distance has to be determined: delta = eY - currentY . 首先,必须确定鼠标距离: delta = eY - currentY
  • Then, snap it into the grid: gridDelta = delta / step * step , where step is 10 in your case. 然后,将其捕捉到网格中: gridDelta = delta / step * step ,其中step为10。

    delta / step represents the number of tones the note is moved. delta / step表示音符移动的音调数。 Because we're using Integers, this value is rounded and we only have whole tones. 因为我们使用的是整数,所以这个值是四舍五入的,我们只有整个音调。 If the mouse is moved 10 (= step) pixels upward, the the next higher tone is chosen. 如果鼠标向上移动10(=步)像素,则选择下一个更高的音调。

    delta / step * step is needed because the distance from one tone to the other is 10, ie the note should appear 10 pixels above its original position if it's moved one tone higher. delta / step * step ,因为从一个音调到另一个音调的距离是10,即如果音符高一个音调,音符应该比其原始位置高10个像素。

  • Next, add gridDelta to this.Top and check if the result is within the range. 接下来,将gridDelta添加到this.Top并检查结果是否在范围内。
  • Finally, save the value into this.Top . 最后,将值保存到this.Top

Maybe numbers make it clearer: If the user presses the mouse button at position Y=14, then drags it up to 48, and then releases, the following happens in the last call of OnDrag : 也许数字更清晰:如果用户在位置Y = 14处按下鼠标按钮,然后将其拖动到48,然后释放,则在OnDrag的最后一次调用中发生以下情况:

  • delta = 48 - 14 - delta is 34. delta = 48 - 14 - delta为34。
  • gridDelta = 34 / 10 * 10 - 34/10 = 3; gridDelta = 34 / 10 * 10 - 34/10 = 3; 3 * 10 * 30 - so gridDelta is 30. 3 * 10 * 30 - 所以gridDelta是30。
  • newTop = this.Top + 30
  • Check whether newTop is within the range, and then assign it to this.Top . 检查newTop是否在该范围内,然后将其分配给this.Top

You see, the note then is exactly 30 pixels above its original position, although the user dragged it for 34 pixels. 你看,然后笔记正好在其原始位置上方30个像素,尽管用户将其拖动了34个像素。

Repetitions like the ones in your code often lead to errors and it's hard to adjust them, so always look for a better algorithm. 代码中的重复通常会导致错误并且很难调整它们,所以总是寻找更好的算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM