首页 / C# / c# – 用鼠标移动矩形
c# – 用鼠标移动矩形
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 用鼠标移动矩形,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1878字,纯文字阅读大概需要3分钟。
内容图文
![c# – 用鼠标移动矩形](/upload/InfoBanner/zyjiaocheng/823/22093846585547b9abeb97b5d762fbf0.jpg)
我写了这段代码:
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);
}
矩形移动,但有反转(它不应该).你能帮我吗?
解决方法:
用于根据鼠标移动移动矩形的鼠标移动处理程序中的数学似乎相当不合适;我想你想要这样的东西:
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# – 用鼠标移动矩形全部内容,希望文章能够帮你解决c# – 用鼠标移动矩形所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。