Reputation: 144
How to draw a line like the windows Paint does, single click for a fixed first point, and the second point (and the line) moves with mouse, another click fixes the line.
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);
}
The clicking event part is fine, but with this method above, the erase line is actually white lines, which overlaps on other background image and previously plotted blue lines.
Is there a more manageable way to make it happen? Thanks
Upvotes: 3
Views: 2593
Reputation: 8890
Any drawing on the form client area should be implemented in the OnPaint event to avoid any strange effects. Consider the following code fragment:
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();
}
Upvotes: 2
Reputation: 7189
Don't try to erase the lines by drawing on top of them. You'll be better off if you draw to an off-screen buffer and on each draw call paint that bitmap to the control. That way you'll get flicker-free graphics and a clean line that works just the way you want it to.
Take a look at this forum post for a good explanation of how you should use the Graphics
class and do drawing in general. There's also a good example program in the end of the post. I suggest you to take a look at that source code after going through the instructions.
Upvotes: 1