http://www.developer.com/

Back to article

Graphics Programming Using C#


July 30, 2002

Graphics plays an important part in every application you develop. For instance, if you are developing a paint application or code-editor software, you will want to add color and font dialog box functionality. Sometimes, you may have to print text in the form areas of the software. There may be cases where you have to decorate your text or place it within a rectangle or inside a circle. You may want to simply insert a picture as the background. The possibilities are endless. This customizations are only possible with the careful and judicious use of the appropriate concepts. This article, which is the first of two parts, explains the concepts as laid out in the Microsoft .NET Framework using C# programming language.

I assume that you have a prior knowledge of C# language, particularly in the area of WinForms. You can locate my two-part article on WinForms from .NET section of this site. Moreover, Windows 2000 is required for testing the codes described in this article along with .NET Framework SDK or Visual Studio .NET.

C# provides us with a rich set of namespaces, classes, methods and events for developing applications with graphical capabilities. With the help of its Graphics class, the System.Drawing namespace provides functionality for drawing shapes, printing texts on to the form, and much more.

The EventHandler involved here is PaintEventHandler and the corresponding event is called Paint. You have to apply the concept of event handling in order to render graphics in your C# program. Listing 1 shown below examines how to print "Welcome C#" on a WinForm. In this example,text is printed directly onto the form.

Listing 1:

using System;
using System.Windows.Forms;
using System.Drawing;

public class Hello:Form  {
  public Hello()   {
    this.Paint += new PaintEventHandler(f1_paint);
  }

  private void f1_paint(object sender,PaintEventArgs e) {

    // Get Graphics Object
    Graphics g = e.Graphics; 

    // Method under System.Drawing.Graphics
    g.DrawString("Welcome C#",new Font("Verdana",20),
    new SolidBrush(Color.Tomato),40,40);
  }

  public static void Main() {
    Application.Run(new Hello());
  }

}

In Listing 1 the method DrawString() takes four arguments. The first argument signifies the text to be printed followed by the font name, size, and color. The next two arguments imply the painting location (X coordinate and Y coordinates) on the form.

Keep in mind that every method in Graphics class has to be accessed by creating an object of that class. You can easily update the above program to render other graphical shapes like rectangle and ellipse. All you have to do is to apply the relevant methods. The next session discusses these methods in detail.

Painting Shapes

With the help of Graphics class of System.Drawing namespace, you can render various kinds of shapes. These include Rectangle, Filled Rectangle, Lines, Ellipse, Filled Ellipse, Pie, Filled Pie, and Polygons. This class defines methods for painting these shapes. Each method differs according to the need of the shapes. You have to learn the syntax of these methods and apply them in your programs. Don't try to memorize all of them, rather you will slowly gain experience by practice.

As already discussed in the earlier, every method on the Graphics class has to be accessed by creating an object of the Graphics class. Table 1 shows some of the methods of this class. You can add the code given on the table in Listing 1.

Purpose

Syntax

Example

Rectangle

DrawRectangle (System.Drawing.Pen, float x, float y, float width, float height)

g.DrawRectangle (new Pen(Color.Pink,3), 15,15,200,150);

 

Filled Rectangle

FillRectangle(System.Drawing.Brush, float x, float y, float width, float height)

g.FillRectangle (new SolidBrush(Color.Pink), 20,20,160,50);

Line

DrawLine(System.Drawing.Pen, float x, float y, float width, float height)

g.DrawLine(new Pen(Color.Pink,3),

15,15,200,150);

Ellipse

DrawEllipse(System.Drawing.Pen, float x, float y, float width, float height)

g.DrawEllipse(new Pen(Color.Pink,3), 15,15,200,150);

Filled Ellipse

FillEllipse(System.Drawing.Brush, float x, float y, float width, float height)

g.FillEllipse (new SolidBrush(Color.Pink), 20,20,160,50);

Pie

DrawPie(System.Drawing.Pen, float x, float y, float width, float height)

g.DrawPie(new Pen(Color.Black),160,30,150,170,100,110)

FilledPie

FillPie(System.Drawing.Brush, float x, float y, float width, float height)

g.FillPie(new Brush(Color.Black),160,30,150,170,100,110)

Polygon

DrawPolygon(System.Drawing.Pen,
new Point[] { new Point(x,y),
new Point(x,y),
new Point(x,y),
new Point(x,y),
new Point(x,y),
new Point(x,y)});

g.DrawPolygon(new Pen(Color.Red,2),
new Point[] { new Point(130,140),
new Point(165,200),
new Point(100,225),
new Point(190,190),
new Point(50,330),
new Point(20,180)});

FilledPolygon

FillPolygon(System.Drawing.Brush,
new Point[] { new Point(x,y),
new Point(x,y),
new Point(x,y),
new Point(x,y),
new Point(x,y),
new Point(x,y)});

g.FillPolygon(new Brush(Color.Red),
new Point[] { new Point(130,140),
new Point(165,200),
new Point(100,225),
new Point(190,190),
new Point(50,330),
new Point(20,180)});

Table 1: Graphics Class Methods

Using the Pen class you can specify color of the border and also the thickness. From the example given above, it can be seen that Pen class is to be applied for drawing shapes while Brush class is applied for filling shapes.

Tweaking the Unit of measurement

As you may know the default Graphics unit is Pixel. By applying the PageUnit property, you can change the unit of measurement to Inch, Millimeter etc as shown below:

Graphics g = e.Graphics;
g.PageUnit = GraphicsUnit.Inch;

Working with Dialog boxes

Dialog boxes are an integral part in any GUI based application. You come across such boxes when you open a file, save a file, pick fonts, pick colors, and so on. These boxes are pre-defined. That means, you only have to apply the relevant coding and rest of the work is done by the .NET runtime. This is a cool way to pick your selection!

If you have ever done Visual Basic or Java programming, you should already be aware of predefined dialog boxes like ColorDialog, FontDialog etc. You may have seen the color dialog box many times if you had used Microsoft Paint. In C#, you can let your user choose a color by applying the standard ColorDialog class. First, you have to create an object of ColorDialog class as shown below:

ColorDialog cd = new ColorDialog();

Using the created object call the ShowDialog() method to display the color dialog box. Finally, invoke the Color property and apply it appropriately as shown in Listing 2:

Listing 2:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Clr:Form  {
  Button b1 = new Button();
  ColorDialog clg = new ColorDialog();

  public Clr()  {
    b1.Click += new EventHandler(b1_click);
    b1.Text = "OK";

    this.Controls.Add(b1);
  }

  public void b1_click(object sender, EventArgs e) {
    clg.ShowDialog();
    this.BackColor = clg.Color;
  }

  public static void Main()  {
    Application.Run(new Clr());
  }
}

In Listing 2, the background color of the form will change as you select a color from the dialog box just like Windows Paint program, where you pick a color for drawing and filling.

Working with FontDialog Box

FontDialog boxes (See Figure 1) enable you to choose the font name, size, styles, and more. You can easily create a font selection dialog box by following the same steps as in the previous listing and by making some minor changes. Listing 3 shown below examines the usage of this useful dialog box:

Listing 3:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Fnt:Form  {
  Button b1 = new Button();
  TextBox tb = new TextBox();
  FontDialog clg = new FontDialog();

  public Fnt()  {
    b1.Click += new EventHandler(b1_click);
    b1.Text = "OK";
    tb.Location = new Point(50,50);

    this.Controls.Add(b1);
    this.Controls.Add(tb);
  }

  public void b1_click(object sender, EventArgs e) {
    clg.ShowDialog();
    tb.Font = clg.Font;
  }

  public static void Main()  {
    Application.Run(new Fnt());
  }
}

Figure 1: Font Selection Box

After executing Listing 3, pick out your font from the dialog box and then type something on the text box. The font inside the text box should reflect your selection.

Summary

In this part of the article, you've seen how to paint text onto the Form. You can try your own font names, sizes and colors by making changes to the above listings. In this part, you have seen a lot of methods along with examples. You have hopely learned how to incorporate these methods into your own program. You also examined some of the pre-defined dialog boxes available to you from the .NET Framework. In the next article you will learn about one of the advanced namespaces of the .NET Framework, System.Drawing2D.

About the Author

Anand Narayanaswamy works as a freelance Web developer and technical writer. He also runs and maintains learnxpress.com, and provides free technical support to users worldwide. He can be reached at anand@learnxpress.com.

# # #

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date