Let the user draw curves and scribble on a PictureBox in C#

The Graphics class provides a DrawLines method that draws a series of connected lines, also called a polyline. This program lets the user create a series of polylines.

The program stores the points that make up a polyline as a List<Point>. It stores a series of polylines in a List<List<Point>>. It keeps track of the new polyline that the user is drawing in the variable NewPolyline.

// The polylines we draw.
private List<List<Point>> Polylines = new List<List<Point>>();

// The new polyline we are drawing.
private List<Point> NewPolyline = null;

When the user presses the mouse down, the following code creates a new polyline.

// Start drawing.
private void picCanvas_MouseDown(object sender, MouseEventArgs e)
{
// Create the new polyline.
NewPolyline = new List<Point>();
Polylines.Add(NewPolyline);

// Add the first point.
NewPolyline.Add(e.Location);
}

When the user moves the mouse, the following code adds the mouse's new location to the new polyline. Notice how the code checks that the user is making a new polyline by checking whether NewPolyline == null.

// Continue drawing.
private void picCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (NewPolyline == null) return;
NewPolyline.Add(e.Location);
picCanvas.Refresh();
}

When the user releases the mouse, the following code removes the new polyline if it contains only a single point.

// Stop drawing.
private void picCanvas_MouseUp(object sender, MouseEventArgs e)
{
if (NewPolyline == null) return;

// See of the new polyline contains more than 1 point.
if (NewPolyline.Count < 2)
{
// Remove it.
Polylines.RemoveAt(Polylines.Count - 1);
}

NewPolyline = null;
picCanvas.Refresh();
}

The only other interesting piece of code in this example is the PictureBox's Paint event handler, which draws the polylines.

// Redraw.
private void picCanvas_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.Clear(picCanvas.BackColor);

// Draw the polylines.
foreach (List<Point> polyline in Polylines)
{
e.Graphics.DrawLines(Pens.Black, polyline.ToArray());
}
}

In the next post, I'll describe a more complicated example that lets the user draw polylines with different colors, line styles, and thicknesses.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.