Skip to main content

Drawing with Graphics in WinForms using C#


This tutorial will show you how to draw various shapes in a Window Form Application using the Graphics namespace. C# version.
Creating graphics in .NET can be very easy. In this tutorial, you will learn how to make a Windows Form Application draw different shapes using built-in methods of System.Drawing.Graphics
We will be creating a form with a PictureBox control and several buttons. These buttons will draw pre-defined shapes using all built-in methods. We will first design our form with one large Picture Box (size: 570, 300), and then add eight buttons to do the following: draw a line, ellipse, rectangle, arc, pie, polygon and bezier, and a button to clear the canvas.
Once we have these controls added to the form, we can begin adding the functionality. Double-click each button on the design view to create the click event handlers for them. First we will instantiate our graphics and pen, then draw a line:
The usage of the majority of the methods are similar, so we assign our graphics variable to the CreateGraphics method on each button click and then use the graphics methods to create the shapes.
The Polygon is slightly different in that we are required to plot the points of each corner before we draw:
The entire code-behind is as follows:
Now when we run this application, we will be able to click each button and see the different shapes appear on the form.

Comments