Drawing on C# forms is very easy we just have to learn a few things first. To draw on C# form we need to first define a graphics object which is simply you can say a canvas or a paper on which we will draw our lines,circles or rectangles etc.
Step 1. Declaring a Graphics Object:
Graphics g;
Here we declared a graphics object g on which we need to draw lines,rectangle circles etc.
Step 2. Define Pen or brush for drawing:
To draw a line we need to declare and initialize a pen first we do this in following fashion
Pen myPen = new Pen(Color.Black,1);
This line defines a pen named ‘myPen’ which has black colour and its nib is 1 pixel wide for a marker like brush use a wider nib giving 5 or 10 as per suits you.
For different coloured pen use in argument one Color.colorName like Color.Red for a red coloured pen.
Step 3. Draw Line:
First we learn how to draw a line. For drawing line we need to define two points between which we intend to draw line defining points is done this way
Point sp = new Point(0,0);//starting point sp
Point ep = new Point(5,5);//ending point ep
Now to draw a line between sp & ep we do this
g = this.CreateGraphics();//tells compiler that we are going to draw on this very form
g.DrawLine(myPen, sp, ep);
We have given drawLine() function 3 arguments pen,sp and ep. A pen to draw with and a starting point and an ending point between which we need to draw a line.
Step 4. Draw Rectangle:
We draw rectangle in similar way but this time using drawRectangle() function with different arguments
Graphic = this.CreateGraphics();
Graphic.DrawRectangle(myPen,x,y,width,height);
We gave it pen to draw with and x(the top right x-coordinate of rectangle),y(the top right y-coordinate of rectangle),width and height.
Step 5. Draw Circle And Ellipse:
For drawing circle there is not any specific method but as we know a circle is an ellipse with both axis of same size or we can say that a circle is an ellipse with same width and height so we use this logic to draw a circle.
Graphic = this.CreateGraphics();
g.DrawEllipse(myPen,x,y,30,30);//you can see here we use 30,30 same width and height to draw a circle if they were different an ellipse would be drawn where as x and y are the upper right coordinates of a rectangle bounding this circle.
Ellipse:
To draw ellipse we use different width and height like
g.DrawEllipse(myPen,x,y,90,30);
That’s all folks. Hope you enjoyed and liked it. If you got any queries regarding drawing in C# feel free to comment it will be appreciated. Thanks!