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();
}
不知道如何删除一条线,当鼠标移动时绘制
答案 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
(通过调用基础实现)和(如果isDrawing
为true
)从startPoint
到currentPoint
的一行您可以订阅OnPaint
Paint
事件而不是覆盖Form1
,而不是像使用鼠标事件处理程序那样订阅