c# 拖拽画线

c# draw lines with dragging

如何像windows画图一样画线,单击固定第一个点,第二个点(和线)随鼠标移动,再单击固定线。

int x = 0, y = 0;
protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);
    // Create the graphics object
    Graphics g = CreateGraphics();
    // Create the pen that will draw the line
    Pen p = new Pen(Color.Navy);
    // Create the pen that will erase the line
    Pen erase = new Pen(Color.White);
    g.DrawLine(erase, 0, 0, x, y);
    // Save the mouse coordinates
    x = e.X; y = e.Y;
    g.DrawLine(p, 0, 0, x, y);
}

点击事件部分没问题,但是用上面这个方法,擦除线实际上是白线,重叠在其他背景图和之前绘制的蓝线上。

有没有更易于管理的方法来实现它?谢谢

不要试图通过在线条上绘画来擦除线条。如果您绘制到屏幕外缓冲区并在每次绘制调用时将该位图绘制到控件,您会过得更好。这样您将获得无闪烁的图形和一条按照您想要的方式工作的简洁线条。

请查看 this forum post,了解您应如何使用 Graphics class 并进行一般绘图的详细说明。 post 末尾还有一个很好的示例程序。我建议您在完成说明后查看该源代码。

窗体客户区的任何绘图都应在 OnPaint 事件中实现,以避免任何奇怪的效果。 考虑以下代码片段:

Point Latest { get; set; }

List<Point> _points = new List<Point>(); 

protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);

    // Save the mouse coordinates
    Latest = new Point(e.X, e.Y);

    // Force to invalidate the form client area and immediately redraw itself. 
    Refresh();
}

protected override void OnPaint(PaintEventArgs e)
{
    var g = e.Graphics;
    base.OnPaint(e);

    if (_points.Count > 0)
    {
        var pen = new Pen(Color.Navy);
        var pt = _points[0];
        for(var i=1; _points.Count > i; i++)
        {
            var next = _points[i];
            g.DrawLine(pen, pt, next);
            pt = next;
        }

        g.DrawLine(pen, pt, Latest);
    }
}

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    Latest = new Point(e.X, e.Y);
    _points.Add(Latest);
    Refresh();
}