C# 3.0 如何使用鼠标在C#中绘制矩形
我想用C#在一个窗体上画一个矩形。我读了之后发现了这个。是否有任何示例或教程可用?这篇文章并不是很有帮助。 链接的文章看起来是C++,这可能解释它为什么对你没有多大帮助。 如果为MouseDown和MouseUp创建事件,则应该具有矩形所需的两个角点。从这里开始,这是一个在表单上绘制的问题。System.Drawing.*可能是您的第一站。下面链接了几个教程:C# 3.0 如何使用鼠标在C#中绘制矩形,c#-3.0,mouse,drawrectangle,C# 3.0,Mouse,Drawrectangle,我想用C#在一个窗体上画一个矩形。我读了之后发现了这个。是否有任何示例或教程可用?这篇文章并不是很有帮助。 链接的文章看起来是C++,这可能解释它为什么对你没有多大帮助。 如果为MouseDown和MouseUp创建事件,则应该具有矩形所需的两个角点。从这里开始,这是一个在表单上绘制的问题。System.Drawing.*可能是您的第一站。下面链接了几个教程: 您需要这3个函数和变量: private Graphics g; Pen pen = new System.Draw
您需要这3个函数和变量:
private Graphics g;
Pen pen = new System.Drawing.Pen(Color.Blue, 2F);
private Rectangle rectangle;
private int posX, posY, width, height;
其次,您需要创建鼠标按下事件:
private void pictureCrop_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
posX = e.X;
posY = e.Y;
}
}
第三,您需要实现鼠标向上移动事件:
private void pictureCrop_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
if (e.X > posX && e.Y > posY) // top left to bottom right
{
width = Math.Abs(e.X - posX);
height = Math.Abs(e.Y - posY);
}
else if (e.X < posX && e.Y < posY) // bottom right to top left
{
width = Math.Abs(posX - e.X);
height = Math.Abs(posY - e.Y);
posX = e.X;
posY = e.Y;
}
else if (e.X < posX && e.Y > posY) // top right to bottom left
{
width = Math.Abs(posX - e.X);
height = Math.Abs(posY - e.Y);
posX = e.X;
}
else if (e.X > posX && e.Y < posY) // bottom left to top right
{
width = Math.Abs(posX - e.X);
height = Math.Abs(posY - e.Y);
posY = e.Y;
}
g.DrawImage(_bitmap, 0, 0);
rectangle = new Rectangle(posX, posY, width, height);
g = pictureCrop.CreateGraphics();
g.DrawRectangle(pen, rectangle);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics graph = e.Graphics;
graph.DrawImage(_bitmap, 0, 0);
Rectangle rec = new Rectangle(posX, posY, width, height);
graph.DrawRectangle(pen, rec);
}