BLOG.CSHARPHELPER.COM: Draw smooth shapes in a form's Paint event handler in C#
Draw smooth shapes in a form's Paint event handler in C#
One of the most common ways to produce a drawing in C# is to draw in the form's Paint event handler. The e.Graphics parameter gives you the Graphics object on which you should draw.
Warning: Don't use the CreateGraphics method to make a Graphics object. That creates an object that you can use to draw on the form right now. When the Paint event handler ends, the system redraws the form using the e.Graphics object so anything you draw with CreateGraphics will disappear before you can even see it. (In fact, you almost ever need to use CreateGraphics.)
The following code draws an ellipse whenever the form is refreshed.
// Draw an ellipse. private void Form1_Paint(object sender, PaintEventArgs e) { // Make the result smooth. e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
// Make a rectangle to bound the ellipse. Rectangle rect = new Rectangle(10, 10, this.ClientSize.Width - 20, this.ClientSize.Height - 20);
// Fill the ellipse with yellow. e.Graphics.FillEllipse(Brushes.Yellow, rect);
// Outline it with a thick red pen. using (Pen thick_pen = new Pen(Color.Red, 5)) { e.Graphics.DrawEllipse(thick_pen, rect); } }
The code first sets the Graphics object's SmoothingMode property to produce smooth drawing. If you don't do this, the result is slightly rougher but it's faster and that's useful if you have a very complicated picture to draw.
Next the code creates a Rectangle to bound the ellipse. Using the same Rectangle to fill and outline the ellipse guarantees that the two line up correctly.
The code then uses FillEllipse to fill the ellipse.
Next the code creates a thick red Pen. The Pen class uses limited system resources so you should always call its Dispose method when you're done with it. The using block calls Dispose automatically when it ends so you don't have to remember to do it yourself. The code uses the DrawEllipse to draw the ellipse's outline with the Pen.
Comments