我想在 C# 中的窗体上绘制一个矩形。我阅读并找到了这篇文章。是否有可用的示例或教程?这篇文章不是很有帮助。
问问题
2229 次
2 回答
3
您链接的文章似乎是 C++,这可以解释为什么它对您没有太大帮助。
如果为 MouseDown 和 MouseUp 创建事件,则应该具有矩形所需的两个角点。从那里开始,这是一个在表格上绘图的问题。System.Drawing.* 应该是您的第一站。下面链接了几个教程:
于 2010-06-30T13:57:29.297 回答
0
您需要这 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);
}
于 2013-12-13T05:25:25.297 回答