Support for graphics in the .NET framework'

Lesson 1: Drawing Graphics

Specify location and size of controls

Required to create forms that dynamically adjust based on user input.

To specify location create Point structure specifying coordinates relative to upper left-corner of form. Use the Point structure to set the controls Location property, e.g.

Button1.Location = new Point(10,10);

The same effect can be achieved via the Left and Top or Right and Bottom properties, but this requires two lines of code e.g.

Button1.Left = 10;

button1.Top = 10;

Specify size via the Size class, e.g.

Button1.Size = new Size(30,30);

Specify colour of controls

Use the Color structure. Simplest to specify using one of the predefined properties within System.Drawing.Color, e.g.

button1.ForeColor = Color.Red;

Specify custom colour using static Color.FromArgb method. Has several overloads, e.g. specify using single 32bit argb value, separate values for red, green and blue, or separate values for alpha, red green and blue, e.g.

Button1.BackColor = Color.FromArgb(200,5,5);

Drawing lines and shapes

To draw on form or control:

  1. Create Graphics object using System.Windows.Forms.Control.CreateGraphics
  2. Create a Pen object
  3. Call member, e.g. DrawEllipse , DrawLine , etc. of Graphics class to draw on control using pen.

To create Graphics class call a controls CreateGraphics method.

Members of the Graphics class expect a Pen object. These are typically created specifying its colour and width in the constructor, e.g.

Graphics g = this.CreateGrapgics();

Pen p = new Pen(Color.Red, 7);

// Draw a line between the two points

g.DrawLine(p, 1, 1, 100, 100);

Graphics.DrawLines, Graphics.DrawPolygon and Graphics.DrawRectangles accept arrays as parameters to allow creation of complex shapes.

Pen Customisation

Besides size and colour (as specified in the constructor) the pattern and endcaps used when drawing the line can be changed. By default solid lines are drawn but this can be changed via the Pen.DashStyle property which takes a value from the DashStyle enumeration (Dash, DashDot, DashDotDot, Dot, Solid). Custom dash patterns can be defined via the Pen.DashOffset and Pen.DashPattern properties. Changing the endcaps allows arrows or callouts to be specified, e.g.

Graphics g = this.CreateGraphics();

Pen p = new Pen(Color.Red, 7);

p.DashStyle = DashStyle.Dot;

p.DrawLine(p, 50, 25, 400, 25);

p.Dashstyle = DashStyle.Solid;

p.StartCap = LineCap.Arrow;

p.EndCap = LineCap.Square;

p.DrawLine(p, 50,50,400,50);

Filling Shapes

For most of the Draw methods the Graphics class has a Fill method that draws a shape and fills in its contents. The Fill methods work like Draw, except they take a Brush instead of a Pen. Note, the Brush is abstract - one of its children (HatchBrush, LinearGradiantBrush, PathGradiantBrush, SolidBrush, TextureBrush) must be used, e.g.

Graphics g = this.CreateGraphics();

Brush b = new SolidBrush(Color.Maroon);

Point[] points = new Point[] {new Point(10,10), new Point(10,100), new Point(50,65), new Point(100,100), new Point(85,40)};

g.FillPolygon(b, points);

To draw filled objects with an outline use the Fill method followed by the Draw method, e.g.

Graphics g = this.CreateGraphics();

Brush b = new SolidBrush(Color.Maroon);

Point[] points = new Point[] {new Point(10,10), new Point(10,100), new Point(50,65), new Point(100,100), new Point(85,40)};

g.FillPolygon(b, points);

g.DrawPolygon(b, points);

To fill an entire Graphics object call the Graphics.Clear method.

Lesson 2: Working With Images

Image and Bitmap classes

The Image class provides ability to create, load, modify and save images such as .bmp, .jpg and .tif files.

Image class is abstract, create instances using Image.FromFile or Image.FromStream. Can also create one of two classes derived from Bitmap for still images or Metafile for animated images.

Bitmap most commonly used for working with new or existing images.

Bitmap contains two particularly useful methods that Image lacks

More complex editing requires creation of Graphics object by calling FromImage method.

Display Pictures

To display image currently residing on disk in a form, load it with Image.FromFile, create a PictureBox control and use the Image to define the PictureBox.BackgroundImage, e.g.

Image i = Image.FromFile(@"c:\windows\gone fishing.bmp");

pictureBox1.BackgroudImage = i;

Alternatively, display image as background to control using the Graphics.DrawImage method, e.g.

Bitmap bm = new Bitmap(@"C:\windows\gone fishing.bmp");

Graphics g = this.CreateGraphics();

g.DrawImage(bm, 1, 1, this.Width, this.Height);

Create and Save Pictures

To create new, blank picture create an instance of the Bitmap class with one of constructors that do not require an existing image. Edit using the SetPixel and FromImage methods.

Save a Bitmap via Save method.

Following code creates 600 * 600 bitmap, draws a shape in it and then saves it as a .jpg file.

Bitmap bm = new Bitmap(600,600);

Graphics g = Graphics.FromImage(bm);

Brush b = new LinearGradientBrush(new Point(1,1), new Point(600, 600), Color.White, Colo.Red);

Point[] points = new Point[] { new Point(10,10), new Point(77,500), new Point(590,100), new Point(250,590), new Point(300,410)};

g.FillPolygon(b, points);

bm.Save("bm.jpg", ImageFormat.Jpeg);

To edit existing image use Bitmap constructor that loads a picture.

Using Icons

Transparent bitmap of specific size. Framework provides standard 40*40 system icons as properties of SystemIcons class. To add icon to form or image call Graphics.DrawIcon or Graphics.DrawIconUnstreched, e.g.

Graphics g = this.CreateGraphics();

g.DrawIcon(SystemIcons.Question, 40, 40);

Can create Bitmap from Icon by calling its ToBitmap method.

Lesson 3: Formatting Text

Add Text To Graphics

  1. Create Graphics object
  2. Create Font object
  3. Optionally create a Brush object
  4. Call Graphics.DrawString specifying location of text

Creating Font Object

Offers 13 constructors. Simplest way is to pass in font family (as string), size (integer) and style (System.Drawing.FontStyle enumeration), e.g.

font f = new Font("Arial", 12, FontStyle.Bold);

Can read font information from a string using the FontConverter, although this is not recommended as the compiler cannot detect errors, e.g.

FontConverter converter = new FontConverter();

Font f = (Font)converter.ConvertFromString("Arial, 12pt")l

Writing text

After creating Font object need to supply Brush object to define how text is filled. Can create own Brush object or use one of the System.Drawing.Brushes properties, e.g.

Graphics g = this.CreateGraphics();

Font f = new Font("Arial", 40, FontStyle.Bold);

g.DrawString("Hello, world!", f, Brushes.Blue, 10, 10);

It is easier to add text to a Form using Label objects, but Graphics.DrawString allows text to be added to Images and Bitmaps.

Control Formatting

StringFormat class provides control over alignment and direction of text. After creating object provide to Graphics.DrawString to control formatting. Most important members of the StringFormat class are:

Alignment - get or set the horizontal text alignment (i.e. to left, centre or right)

FormatFlags - an enumeration containing formatting information, such as direction test is displayed in, whether it is vertically aligned, if portions of text outside of the formatting rectangle are clipped, etc.

LineAlignment - controls vertical text alignment (i.e. top, centre or bottom)

Trimming - enumeration specifying how strings are trimmed, e.g. To the nearest character, nearest word, that no trimming takes place, etc.