BLOG.CSHARPHELPER.COM: Let the user draw rubber band ellipses (or other shapes) in C#
Let the user draw rubber band ellipses (or other shapes) in C#
The following code shows how the program draws ellipses.
// The ellipses to draw. private List Ellipses = new List();
// The points for the new ellipse we are drawing. private Point StartPoint, EndPoint; private bool DrawingNew = false;
// Draw the current ellipses. private void picCanvas_Paint( object sender, PaintEventArgs e) { // Draw the existing ellipses. foreach (Rectangle rect in Ellipses) { e.Graphics.DrawEllipse(Pens.Black, rect); }
// If we are creating a new ellipse, draw it. if (DrawingNew) { using (Pen dashed_pen = new Pen(Color.Green, 0)) { dashed_pen.DashStyle = DashStyle.Custom; dashed_pen.DashPattern = new float[] { 5, 5 }; Rectangle rect = new Rectangle( Math.Min(StartPoint.X, EndPoint.X), Math.Min(StartPoint.Y, EndPoint.Y), Math.Abs(StartPoint.X - EndPoint.X), Math.Abs(StartPoint.Y - EndPoint.Y)); e.Graphics.DrawEllipse(dashed_pen, rect); } } }
The program represents ellipses with Rectangles stored in the Ellipses list. It represents the starting and ending corners with the variables StartPoint and EndPoint.
When the Paint event handler occurs, the program loops through the Ellipses collection drawing each ellipse. Then if the program is currently drawing a new ellipse, the code creates a brush, sets its dash pattern to produce long dashes, and draws the new ellipse.
The following code shows the PictureBox's MouseDown, MouseMove, and MouseUp event handlers.
// Continue drawing the new ellipse. private void picCanvas_MouseMove(object sender, MouseEventArgs e) { if (!DrawingNew) return; EndPoint = e.Location; picCanvas.Refresh(); }
// Finish drawing the new ellipse. private void picCanvas_MouseUp(object sender, MouseEventArgs e) { if (!DrawingNew) return; DrawingNew = false;
// If the start and end points are different, // save the new ellipse. if (StartPoint.X != EndPoint.X && StartPoint.Y != EndPoint.Y) { Rectangle rect = new Rectangle( Math.Min(StartPoint.X, EndPoint.X), Math.Min(StartPoint.Y, EndPoint.Y), Math.Abs(StartPoint.X - EndPoint.X), Math.Abs(StartPoint.Y - EndPoint.Y)); Ellipses.Add(rect); }
picCanvas.Refresh(); }
The MouseDown event handler saves the mouse's position in the StartPoint variable and sets DrawingNew = true.
If DrawingNew is true, the MouseMove event handler updates EndPoint to the mouse's current location and the refreshes the PictureBox.
If DrawingNew is true, the MouseUp event handler determines whether the new ellipse has a non-zero width and height and, if it does, adds the new ellipse to the Ellipses list. It then refreshes the PictureBox.
You can use similar techniques to let the user draw just about anything: rectangles, lines, stars, or whatever shape you like. Just change the code that does the drawing in the Paint event handler.
Comments