我有这个代码:
private void pictureBoxSnap_Paint(object sender, PaintEventArgs e)
{
if (pictureBoxSnap.Image != null)
{
if (btn == true)
{
if (Rect != null && Rect.Width > 0 && Rect.Height > 0)
{
e.Graphics.DrawRectangle(pen, Rect);
}
}
}
}
private void pictureBoxSnap_MouseMove(object sender, MouseEventArgs e)
{
if (btn == true)
{
if (e.Button == MouseButtons.Left)
return;
Point tempEndPoint = e.Location;
Rect.Location = new Point(
Math.Min(RectStartPoint.X, tempEndPoint.X),
Math.Min(RectStartPoint.Y, tempEndPoint.Y));
Rect.Size = new Size(
Math.Abs(RectStartPoint.X - tempEndPoint.X),
Math.Abs(RectStartPoint.Y - tempEndPoint.Y));
pictureBoxSnap.Invalidate();
}
}
private void pictureBoxSnap_MouseDown(object sender, MouseEventArgs e)
{
btn = !btn;
}
我想做的是两件事:
当我第一次点击鼠标左键时RectStartPoint X
and Y
应该是鼠标光标现在所在的位置。然后我移动鼠标,矩形会变大或变小,然后当我再次单击鼠标左键时,将矩形保留为上次鼠标光标所在的大小。我怎样才能得到它?
现在一切都开始于0,0 the RectStartPoint
将0,0如果我把它改成e.Location.X
and Y
反而RectStartPoint
它不会画任何东西。
第二件事是,当我第一次单击鼠标左键并更改矩形大小时,如果我继续移动鼠标,同时再次单击鼠标左键,则矩形将消失/删除。如果我不移动鼠标,仅单击左键,则矩形将保留。为什么我移动鼠标的同时点击左键矩形会被删除?
我不太确定你想从你的问题中得到什么。下面的代码执行经典的橡皮筋操作:它绘制一个实时矩形,并在您单击而不移动时将其删除。
我把计算放在一个灵活的函数中。
bool btn = false;
Point RectStartPoint = Point.Empty;
Point RectEndPoint = Point.Empty;
private void pictureBoxSnap_Paint(object sender, PaintEventArgs e)
{
if (pictureBoxSnap.Image != null)
{
{
Rectangle Rect = getRect(RectStartPoint, RectEndPoint); ;
if (Rect != Rectangle.Empty)
{
e.Graphics.DrawRectangle(Pens.Firebrick, Rect);
}
}
}
}
private void pictureBoxSnap_MouseMove(object sender, MouseEventArgs e)
{
if (btn == true)
{
RectEndPoint = e.Location;
pictureBoxSnap.Invalidate();
}
}
private void pictureBoxSnap_MouseDown(object sender, MouseEventArgs e)
{
RectStartPoint = e.Location;
btn = true;
}
private void pictureBoxSnap_MouseUp(object sender, MouseEventArgs e)
{
btn = false;
RectEndPoint = e.Location;
pictureBoxSnap.Invalidate();
}
Rectangle getRect(Point p1, Point p2)
{
Point p = new Point(Math.Min(p1.X, p2.X),Math.Min(p1.Y, p2.Y) );
Size s = new Size(Math.Abs(p1.X - p2.X), Math.Abs(p1.Y - p2.Y));
return new Rectangle(p, s);
}
注 1:PictureBox 控件已经是双缓冲的,因此无论您绘制的速度多快或多大,它都不会闪烁。
注 2:您可能需要更彻底地检查鼠标按钮是否会涉及到右侧(或中间)按钮。这是“正确”检查的示例:
if (e.Button & MouseButtons.Left != MouseButtons.None) ..
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)