Tic*_*ksy 5 c# move selection winforms
我写了这段代码:
private struct MovePoint
{
public int X;
public int Y;
}
private void Image_MouseDown(object sender, MouseEventArgs e)
{
FirstPoint = new MovePoint();
FirstPoint.X = e.X;
FirstPoint.Y = e.Y;
}
private void Image_MouseMove(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
if(FirstPoint.X > e.X)
{
Rectangle.X = FirstPoint.X - e.X;
//Rectangle.Width -= FirstPoint.X - e.X;
} else
{
Rectangle.X = FirstPoint.X + e.X;
//Rectangle.Width += FirstPoint.X + e.X;
}
if(FirstPoint.Y > e.Y)
{
Rectangle.Y = FirstPoint.Y - e.Y;
//Rectangle.Height -= FirstPoint.Y - e.Y;
} else
{
Rectangle.Y = FirstPoint.Y + e.Y;
//Rectangle.Height += FirstPoint.Y + e.Y;
}
Image.Invalidate();
}
}
private void Image_Paint(object sender, PaintEventArgs e)
{
if(Pen != null) e.Graphics.DrawRectangle(Pen, Rectangle);
}
Run Code Online (Sandbox Code Playgroud)
矩形移动,但有反转(它不应该).你能帮我吗?
用于根据鼠标移动移动矩形的鼠标移动处理程序中的数学似乎相当不合适; 我想你想要这样的东西:
private void Image_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int initialX = 0, initialY = 0; // for example.
Rectangle.X = (e.X - FirstPoint.X) + initialX;
Rectangle.Y = (e.Y - FirstPoint.Y) + initialY;
Image.Invalidate();
}
}
Run Code Online (Sandbox Code Playgroud)
这样,矩形的左上角将跟随鼠标,方法是跟踪初始鼠标按下位置和当前鼠标位置之间的差值.但请注意,每次重新单击并拖动时,矩形将移回其原始位置.
相反,如果您希望Rectangle在多次单击并拖动操作中"记住"其位置(即,不要在鼠标按下时重新初始化到其初始位置),您可以执行以下操作:
private void Image_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// Increment rectangle-location by mouse-location delta.
Rectangle.X += e.X - FirstPoint.X;
Rectangle.Y += e.Y - FirstPoint.Y;
// Re-calibrate on each move operation.
FirstPoint = new MovePoint { X = e.X, Y = e.Y };
Image.Invalidate();
}
}
Run Code Online (Sandbox Code Playgroud)
另一个建议:MovePoint当已经存在类型时,不需要创建自己的System.Drawing.Point类型.此外,通常,尽量不要创建可变结构.
| 归档时间: |
|
| 查看次数: |
8725 次 |
| 最近记录: |