C# Drawing Graphics in a Form

We need the System.Drawing namespace.

The place to start is with the CreateGraphics() method.

This is a method of the Control class. Thus, in a form, we use

     this.CreateGraphics();

which returns an instance of the Graphics class.

In drawing, we do not want to try to go past the edge of the form itself. We can find out the dimensions of the form using the Size property of the Form class. The value of Size is a Size structure, which stores a pair of integers Height and Width.


Graphics Class

This is the fundamental class involved in drawing anything. Some methods:

There are many more draw and fill methods. In general, we draw with a pen and fill with a brush.

In all these cases in which we have (x, y) to specify a point, we could instead be using the Point structure. Thus we also have methods such as:

     public void DrawLine(Pen pen, Point First, Point Second)


Color Struct

This is in the System.Drawing namespace.

Colors are expressed as 4-byte numbers, with one byte each for red, green and blue and one byte for the degree of transparency.

The Color struct has a large number of static properties named after various individual shades such as Cyan, DarkSeaGreen or Gold (all get only).

It also has some non-static properties R, G and B (also all get only), which return integer values = the red, green and blue components of a specific Color.

There are methods such as:

public static Color FromArgb(int red, int green, int blue)

This creates a color from the values of the arguments, which are limited to 0 through 255.

Note: elsewhere we also have a Color enumeration and a Color class. The Color struct is the one we need for graphics.


Pen Class

We use a Pen object to draw lines and curves.

Constructors:

Properties:


Rectangle Class

One of the constructors is:

     public Rectangle(int x, int y, int width, int height)

where x = x-coordinate of the upper left-hand corner and y = y-coordinate of$

Notice that this creates the object but it has not yet been drawn.


Brush Class and SolidBrush Class

We use a brush to fill a closed object we drew earlier with a pen.

The Brush class is a base class from which there are several derived classes for different kinds of brushes. We shall consider just one of them, the SolidColorbrush. It has constructors:

The SolidBrush Class has one property, Color, and fills in a region solidly with that color.


Point Structure and Size Structure

This is used to store one point.

Constructors:

Properties:

The Size structure stores a pair of integers, Height and Width, and has an initializing constructor:

     Size(int H, int W)