无法删除c#中的绘图线

时间:2016-03-20 15:10:06

标签: c#

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
  isDrawing = true;

  currentPoint = e.Location;
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            Graphics bedLine = this.CreateGraphics();
            Pen bedp = new Pen(Color.Blue, 2);
            if (isDrawing)
            {
                bedLine.DrawLine(bedp, currentPoint, e.Location);
                currentPoint = e.Location;
            }
            bedp.Dispose();
        }

不知道如何删除一条线,当鼠标移动时绘制

1 个答案:

答案 0 :(得分:2)

OnPaint之外的任何其他方法绘制表单是个坏主意。你不能删除一行,它只能被抽出。

因此,您应该使用覆盖OnPaint方法完成所有绘图。我建议如下:

public partial class Form1
{
    private bool isDrawing;
    private Point startPoint;
    private Point currentPoint;

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        isDrawing = true;
        startPoint = e.Location; // remember the starting point
    }

    // subscribe this to the MouseUp event of Form1
    private void Form1_MouseUp(object sender, EventArgs e)
    {
        isDrawing = false;
        Invalidate(); // tell Form1 to redraw!
    }
    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        currentPoint = e.Location; // save current point
        Invalidate(); // tell Form1 to redraw!
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e); // call base implementation
        if (!isDrawing) return; // no line drawing needed

        // draw line from startPoint to currentPoint
        using (Pen bedp = new Pen(Color.Blue, 2))
            e.Graphics.DrawLine(bedp, startPoint, currentPoint);
    }
}

这就是:

  • 按下鼠标时,我们会在startPoint中保存该位置,并将isDrawing设置为true
  • 移动鼠标时,我们会在currentPoint中保存新点并致电Invalidate告诉Form1它应该重新绘制
  • 当鼠标被释放时,我们会将isDrawing重置为false并再次致电Invalidate以重新绘制Form1而无需行
  • OnPaint绘制Form1(通过调用基础实现)和(如果isDrawingtrue)从startPointcurrentPoint的一行

您可以订阅OnPaint Paint事件而不是覆盖Form1,而不是像使用鼠标事件处理程序那样订阅