我在图片框上有很多标签。我想相对于光标移动标签,但是当在移动方向上有另一个标签时,标签应停止移动
这是我的代码
void lbl_MouseClick(object sender, MouseEventArgs e)
{
try
{
lblCutPaste = sender as Control;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
void lbl_MouseDown(object sender, MouseEventArgs e)
{
try
{
activeControl = sender as Control;
previousLocation = e.Location;
// preloc = activeControl.Location;
Cursor = Cursors.Hand;
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
void lbl_MouseMove(object sender, MouseEventArgs e)
{
try
{
bool isCollide = false;
if (activeControl == null || activeControl != sender)
return;
var location = activeControl.Location;
location.Offset(e.Location.X - previousLocation.X, e.Location.Y - previousLocation.Y);
if (location.X >= 0 && location.X <= activeControl.Parent.Width - activeControl.Width && location.Y >= 0 && location.Y <= activeControl.Parent.Height - activeControl.Height)
{
activeControl.Location = location;
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
void lbl_MouseUp(object sender, MouseEventArgs e)
{
activeControl = null;
Cursor = Cursors.Default;
}
这是一个工作示例;您必须在研究代码后对代码进行修改。将lambda引入事件中应该不难。
首先创建20个,Labels
然后将它们添加到上PictureBox
。它Label
与三个事件相关联。Label
当它被拖动时,它为活动对象上色。
每个Label
都还被添加到一个类级别,List<T>
因此我们可以轻松地进行所需的检查。该检查使用LINQ来计数所有重叠的标签。
它使用Rectangle.IntersectsWith
和Point.Subtract
方法..
List<Label> myLabels = new List<Label>();
Label movingLabel = null;
Point mDown = Point.Empty;
private void button11_Click(object sender, EventArgs e)
{
Random R = new Random(8);
Size sz = pictureBox1.ClientSize;
for (int i = 0; i < 20; i++)
{
Label lbl = new Label() {Text = "L " + i};
lbl.Location = new Point(R.Next(sz.Width), R.Next(sz.Height));
lbl.Parent = pictureBox1;
myLabels.Add(lbl);
lbl.BorderStyle = BorderStyle.FixedSingle;
lbl.MouseDown += (ss, ee) =>
{
movingLabel = lbl;
lbl.BackColor = Color.Bisque;
mDown = ee.Location;
};
lbl.MouseMove += (ss, ee) =>
{
if (ee.Button == MouseButtons.Left)
{
Point nLoc = Point.Subtract(lbl.Location,
new Size(mDown.X - ee.X, mDown.Y - ee.Y));
Rectangle rlbNew = new Rectangle(nLoc, lbl.Size);
var overlapped = myLabels.Where(x => x != lbl &&
rlbNew.IntersectsWith(new Rectangle(x.Location, x.Size)));
if (overlapped.Count() == 0) lbl.Location = nLoc;
}
};
lbl.MouseUp += (ss, ee) =>
{
movingLabel = null;
lbl.BackColor = Color.Transparent;
};
}
}
请注意,我不在乎所创建的对象是否Labels
重叠,因此除非您不断拖动直到达到“合法”的对象,否则某些对象确实不能重叠。然后它将跳过重叠的标签并移至新位置。
如果您希望对逻辑进行编码以允许在移动时发生重叠,请将红色设为底色,以表明这样做不可行,MouseUp
如果仍然重叠,则让其跳回去。您将需要为此存储原始位置。但是,将其拖到合法位置可能就足够了,imo。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句