gpt4 book ai didi

c# - 用鼠标 move 矩形

转载 作者:太空狗 更新时间:2023-10-29 23:17:14 25 4
gpt4 key购买 nike

我写了这段代码:

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);
}

矩形 move ,但有反转(不应该)。你能帮忙吗?

最佳答案

鼠标 move 处理程序中用于根据鼠标 move move 矩形的数学运算似乎很不合理;我想你想要这样的东西:

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();
}
}

这样,矩形的左上角将通过跟踪初始 鼠标按下位置和当前 鼠标位置之间的增量来跟随鼠标。但请注意,每次您重新单击并拖动时,矩形都会移回其原始位置。

相反,如果您希望 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();
}
}

另一个建议:当已有 System.Drawing.Point 类型时,无需创建您自己的 MovePoint 类型。另外,一般来说,尽量不要创建可变结构。

关于c# - 用鼠标 move 矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8637407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com