我有一个 C# 中的 Windows 窗体应用程序,带有绘图面板和一个按钮 - 用于绘制一条线。
单击按钮时,您可以为 2 个随机点绘制一条线。
Pen p = new Pen(Color.Black, 5);
//point for start
Point ps = new Point();
//point for end
Point pe = new Point();
private void drawPanel_MouseDown(object sender, MouseEventArgs e)
{
ps.X = e.X;
ps.Y = e.Y;
pe = ps;
}
private void drawPanel_MouseMove(object sender, MouseEventArgs e)
{
// when button is clicked for drawing draw = true;
if (draw)
{
if (e.Button == MouseButtons.Left)
{
pe = new Point(e.X, e.Y);
}
}
}
private void drawPanel_MouseUp(object sender, MouseEventArgs e)
{
onMouseUpFlag = true;
}
private void drawPanel_Paint(object sender, PaintEventArgs e)
{
Graphics g = drawPanel.CreateGraphics();
if (onMouseUpFlag)
{
g.DrawLine(p, ps, pe);
g.Dispose();
}
}
该程序有一些缺陷:
- 当你画一条线时,它会显示它,只有当主窗口移动到某个地方时(通常是当我隐藏它时)
- 它只能绘制 1 条线。
任何建议如何解决这些错误?
编辑
我已经阅读了您的答案并进行了一些更改:
Pen p = new Pen(Color.Black, 5);
Point ps = new Point();
Point pe = new Point();
List<Point> linesStart= new List<Point>();
List<Point> linesEnd= new List<Point>();
private void drawPanel_MouseDown(object sender, MouseEventArgs e)
{
ps.X = e.X;
ps.Y = e.Y;
linesStart.Add(ps);
pe = ps;
}
private void drawPanel_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
pe = new Point(e.X, e.Y);
//adding end point .. actually adds a lot of points
linesEnd.Add(pe);
}
}
bool onMouseUpFlag = false;
private void drawPanel_MouseUp(object sender, MouseEventArgs e)
{
onMouseUpFlag = true;
drawPanel.Invalidate();
}
private void drawPanel_Paint(object sender, PaintEventArgs e)
{
if (onMouseUpFlag)
{
for (int i = 0; i < linesStart.Count; i++)
{
e.Graphics.DrawLine(p, linesStart[i], linesEnd[i]);
}
}
}
现在我正在尝试为多条线修复 DrawLine。Paint 事件可以做多行,但只有起点是好的。不知何故,终点不是很正确。在哪里可以准确设置 MouseMove 事件的最后一点?