如何绘制直线到鼠标坐标

本文关键字:鼠标 坐标 何绘制 绘制 | 更新日期: 2023-09-27 18:01:12

当用户按下左键并移动鼠标时,从上一点到当前鼠标移动位置应该显示一条直线(而不是永久线(。最后,当用户释放鼠标左键时,会出现一条真正的直线。请帮帮我。。我该怎么做?

      List<Point> points = new List<Point>();
     private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
      {
         if (e.Button == MouseButtons.Left)
       {
           points.Add(e.Location);
           pictureBox1.Invalidate();
       }
     }
    private void pictureBox1_Paint(object sender, PaintEventArgs e)
     {
         if (points.Count > 1)
         e.Graphics.DrawLines(Pens.Black, points.ToArray());
     }

如何绘制直线到鼠标坐标

这就是您想要的

private Stack<Point> points = new Stack<Point>();
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    points.Clear();
    points.Push(e.Location);
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (points.Count > 1)
    {
        points.Pop();
    }
    if (points.Count > 0 && e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        points.Push(e.Location);
        pictureBox1.Invalidate();
    }
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (points.Count > 1)
        e.Graphics.DrawLines(Pens.Black, points.ToArray());
}

我使用Stack是为了方便使用,您可以自由更改为您选择的任何集合。

要画几条线,你可以做这样的

private Stack<Line> lines = new Stack<Line>();
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    lines.Push(new Line { Start = e.Location });
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (lines.Count > 0 && e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        lines.Peek().End = e.Location;
        pictureBox1.Invalidate();
    }
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    foreach (var line in lines)
    {
        e.Graphics.DrawLine(Pens.Black, line.Start, line.End);
    }
}
class Line
{
    public Point Start { get; set; }
    public Point End { get; set; }
}

您可以使用上述代码

 Point currentPoint = new Point();
  private void Canvas_MouseDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (e.ButtonState == MouseButtonState.Pressed)
            currentPoint = e.GetPosition(this);
    }
    private void Canvas_MouseMove_1(object sender, System.Windows.Input.MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            Line line = new Line();
            line.Stroke = SystemColors.WindowFrameBrush;
            line.X1 = currentPoint.X;
            line.Y1 = currentPoint.Y;
            line.X2 = e.GetPosition(this).X;
            line.Y2 = e.GetPosition(this).Y;
            currentPoint = e.GetPosition(this);
            paintSurface.Children.Add(line);
        }
    }