Drawing on a form with the Graphics object
You need to create a Graphics object before you can draw anything on a form. This is done using the CreateGraphics method.
Drawing a line with the Pen object
You also need a Pen object. When you create a Pen object, you can specify which Brush colour you want to use and the width of the line. You can then call the DrawLine method of the Graphics object. This must be passed parameters which include the Pen object, the X and Y coordinates of the start of the line, and the X and Y coordinates of the end of the line.
The following program draws a diagonal line when a button on a form is pressed:
Try this: Draw five violet coloured, horizontal, parallel lines
Draw a rectangle
You can draw other shapes too. For example, to draw a rectangle you can call the DrawRectangle method of the Graphics object, passing it a Pen object, X and Y coordinates of the top left corner, the width and the height:
You can also set other properties of the Pen object before using it with the Graphics object to draw something. For example, if you want a dotted line, or a rectangle with a dotted boarder:
Try this: Create a second Pen object called myPen2 and use it to draw a rectangle whose boarder is an olive green dashed line.
Draw an ellipse
One way to draw an ellipse (or a circle), is to first draw a rectangle (or a square) to serve as its container. One you have a rectangle, you can then draw the ellipses as follows:
You can also draw an ellipse without defining a rectangle object, but it still helps to think of the ellipse being inside a rectangle whose upper left corner you must specify, along with the width and height of the ellipse:
Try this: Draw three equal sized circles side by side (touching each other)
Drawing solid shapes with the Brush object
To draw a solid shape you need a Brush object whose colour you can specify when you create it. Then, instead of calling the DrawShape method and passing it a Pen, you call the FillShape method and pass it the Brush, for example to create a solid red ellipse:
If you want a line around the shape, you must draw that separately with a Pen:
Try this: Draw a solid red square with a smaller solid yellow circle in the centre of it
Extension Task
Draw a circle using a custom colour (based on RGB values).