Home

Introduction to GDI+

 

Device Contexts

 

Introduction to GDI

Microsoft Windows is a graphics-oriented operating system. It uses shapes, pictures, lines, colors, and various types of variations to convey the impression of physical objects. When we stare at a flat screen built in front of a monitor filled with insignificant wires, we believe that we are looking at physical buildings or real people. This is done through smart and effective representations that have made computer use nowadays become fun and useful.

To support the ability to represent pictures and other visual features, Microsoft in the beginning provided a library called the Graphical Device Interface or GDI. To face the new requirements as computer use became more and more demanding, Microsoft upgraded the GDI with GDI+. GDI+ is the graphical library used in the .NET Framework.

You use GDI by drawing shapes or displaying pictures in your application.

Human Being

Introduction to Device Contexts

To draw something, you need a platform on which to draw and one or a few tools to draw with. The most common platform on which to draw is probably a piece of paper. Besides such a platform, you may need a pen or a brush that would show the evolution of the drawing work on the platform. Since a pen can have or use only one color, depending on your goal, one pen may not be sufficient, in which case you would end up with quite a few of them.

A device context is an ensemble of the platform you draw on and the tools you need to draw with. It also includes the dimensioning of the platform, the orientation and other variations of your drawing, the colors, and various other accessories that you can use to express your imagination.

When using a computer, you certainly cannot position tools on the table or desktop to use as needed. To help with drawing on the Windows operating system, Microsoft created the Graphical Device Interface, abbreviated as GDI. It is a set of classes, functions, variables, and constants that group all or most of everything you need to draw on an application. GDI is provided as a library called Gdi.dll and is already installed on your computer.

The GDI+ Library

GDI+ is the system used to perform drawing and other related graphics operations for the Microsoft Windows family of operating systems. Its predecessor was the Graphical Device Interface (GDI), which has therefore been replaced, namely with the new operating systems such as Windows XP, Windows Server 2003, or Windows Vista. The + in GDI+ indicates that it provides a significant improvement to GDI. It adds new features that were not available in GDI and were therefore difficult to produce. GDI+ allows you to create device-independent applications without worrying about the hardware on which the application would run.

GDI+ is inherently installed in Microsoft Windows XP, Windows Server 2003, and Windows Vista. To use it on previous operating systems, it must be explicitly distributed. GDI+ provides its functionality through three fronts:

  • Vector Graphics
    This is the area that consists of drawing and manipulating geometric-based and related figures including lines, combinations of lines, round and quadrilateral shapes. These are treated as sets of points on a screen or other device. To perform these types of operations, the GDI+ system provides various classes that perform different assignments. For example, one class can be in charge of creating or preparing tools used to draw. Another class can be used to perform the actual drawing, using the provided tools
  • Imaging
    While it may appear easy to create vector graphics that are made of easily recognizable colors, advanced pictures present a challenge to display or draw them on a device. For these reasons, imaging is the area used to deal with such complex operations
  • Typography
     
    Typography consists of creating, manipulating or making fonts available to an application

Getting to GDI+ 

 

The Graphics Platform

To draw in GDI, you have to obtain a handle to the device context. This is done by declaring a variable or a pointer to HDC then calling a function such as BeginPaint() to initialize the device context. You also have to create the tools needed to draw. For example, you have to create a pen and/or a brush. Once the tools are ready, you have to select them into the device context to make them available. After drawing, it is suggested that you release the device context.

To draw in GDI+, you use an object referred to as graphic.

GDI+ Related Namespaces

To support GDI+ graphics and their features, the .NET Framework provides the System.Drawing namespace that is is created in the System.Drawing.dll library. This namespace also contains classes to draw or define a font in an application. To enhance the aspects of a drawing, the .NET Framework provides additional classes in the System.Drawing.Drawing2D namespace. This namespace also is defined in the System.Drawing.dll assembly. To support additional manipulation techniques that can be applied to a picture, the .NET Framework provides some other classes in the System.Drawing.Imaging namespace, which is also part of the System.Drawing.dll library.

The Graphics Object

 

Introduction

The main object on which you will perform most drawings is called a graphic. In most cases, this object is not readily available when you need it: you must request it from the object on which you want to draw or you must create it. Both operations are highly easy.

Getting a Graphic Object

In GDI+, a graphic object is based on a class called Graphics. This class is defined in the System.Drawing namespace. Before drawing, you should obtain a graphic object. Fortunately, every Windows control, that is, every object based on the Control class, automatically inherits a method called CreateGraphics(), which gives you access to the graphic part of a control. The syntax of the Control.CreateGraphics() method is:

public Graphics CreateGraphics();

As you can see, the CreateGraphics() method returns the Graphics object of the variable you call it from. Here is an example of getting the Graphics object of a form:

private void button1_Click(object sender, EventArgs e)
{
            Graphics graph = CreateGraphics();
}

Another technique you can use to get the Graphics object of a control is to call the Graphics.FromHwnd() static method. Its syntax is:

public static Graphics FromHwnd(IntPtr hwnd);

Remember that this method is static. The argument passed to it must be a handle to the object whose Graphics object you want to access. Every Windows control has a handle called Handle. Here is an example of using it to get the Graphics part of a form:

private void button1_Click(object sender, EventArgs e)
{
            Graphics graph = Graphics.FromHwnd(this.Handle);
}

If you are using the Paint event of a window, it provides a readily available Graphics object from its PaintEventArgs argument. You can access the Graphics object as follows:

private void Form1_Paint(object sender, PaintEventArgs e)
{
            e.Graphics . . . 
} 

The Process of Drawing

 

Getting a Device Context

As mentioned above, before drawing, make sure you have a Graphics object, which depends on your approach to drawing. To actually perform the drawing, the Graphics class provides various methods adapted for different shapes. Each method used to draw something has a name that starts with Draw... Also, each method that is used to draw a known shape requires a Pen argument. Therefore, when drawing, your first decision will be based on the shape or type of figure you want to draw.

Two other pieces of information are particularly important with regards to any figure or shape you will need to draw: its location and dimensions.

The Starting Point of a Shape or Figure

To keep track of the various drawings, the object on which you draw uses a coordinate system that has its origin (0, 0) on its top-left corner. If you are drawing on a form, this origin is positioned just under the title bar to the left:

The origin of the coordinate system and its axes

How you specify the values of the starting point of a shape or figure depends on the shape.

Device Objects: An Icon

 

Introduction

An icon is used to display graphics on window objects. While a picture can have any dimension, the size of an icon is limited. This is because icons assume different roles on an application.

Icons are used to represent folders in Windows Explorer and My Computer:

Windows Explorer or My Computer
 

Creating Icons

To create an icon, you can use any application that has the capability. Normally, you can use Microsoft Visual Studio 2005 to create or design an icon. To do this, on the main menu, you can click Project -> Add New Item... In the Templates list, you can click Icon, give it a name, and click Add. You would then receive a platform to design an icon.

When you start designing an icon, you would be presented with a drawing area whose dimensions are 32 x 32 pixels. This is the size of the icon that displays as Large Icon. Here is an example from the New File dialog box of Microsoft Visual Studio 2005 in the Templates list:

Add New Item

In some cases, you may allow the user to display smaller icons, which are 16x16 pixels:

Add New Item

To make this possible, you can associate a second icon to the 32x32 one. The application you use to design your icon should make it simple for you to add this second icon. To do this in Microsoft Visual Studio 2005, while the icon is displaying:

  • On the main menu, you can click Image -> New Image Type...
  • You can right-click an empty area in the icon window and click New Image Type...

When the New Icon Image Type dialog box comes up, you can click 16x16, 16 colors and click OK. Whether you create only one or both versions of the icon, both are stored in a single file whose extension is .ico

Practical LearningPractical Learning: Introducing GDI+ Resources

  1. Start Microsoft Visual C# and create a new Windows Application named Resources1
  2. On the main menu, click Project -> Add New Item...
  3. In the Templates list, click Icon File
  4. Set the name to diamond and click Add
  5. On the main menu, click File -> Save diamond.ico As...
  6. Locate and display the bin sub-folder of your project
  7. Double-click Debug to select that folder
  8. Click Save
  9. If the Colors window is not displaying, on the main menu, click Image -> Show Colors Window.
    On the Colors window, click the small green monitor
  10. On the Image Editor toolbar, click the Erase Tool and wipe the whole drawing area
  11. On the Image Editor toolbar, click the Line button Line
  12. In the Colors Palette, click the blue color
  13. In the empty drawing area, count 15 small boxes from the top left to the right. In the 16th box, click and drag right and down for an angle of 45˚ for 7 boxes. Release the mouse
  14. Click the next small box on the right side of the top blue box then drag left and down at 45˚ for 7 boxes:
     
    Icon Design
  15. Using the tools of Image Editor toolbar, complete the design as follows:
     
  16. To design the 16x16 pixel version of the icon, right-click a white area in the drawing section and click New Image Type
  17. In the New Icon Image Type dialog box, click 16x16, 16 Colors if necessary and click OK
     
    New Icon Type
  18. Design the icon as follows:
     
    Icon Design: Diamond
  19. Save the file

Using an Icon

To support icons, the GDI+ library provides the Icon class, which is defined in the System.Drawing namespace. To use an icon in your application, you can first declare a variable of type Icon using one of the class' constructors. If the icon is stored in a file, the simplest constructor to use has the following syntax:

public Icon(string filename);

With this constructor, the name of, or the path to, the icon file is passed as argument.

After creating the icon, if you want to use only one size version, you can use one the following constructors to declare the variable:

public Icon(Icon original, Size size);
public Icon(Icon original, int width, int height);

After initializing an Icon variable, if you want to get its dimensions, you can access its Width and its Height properties, or its Size property.

As mentioned already, there are various ways an icon can be used. For example, you can display it in a control by drawing it. To do this, you can call the Graphics.DrawIcon() method which is overloaded with two versions whose syntaxes are:

public void DrawIcon(Icon icon, Rectangle targetRect);
public void DrawIcon(Icon icon, int x, int y);

The first version allows you to specify the location and dimensions of the icon. Here is an example of calling it:

private void btnGrapher_Click(object sender, EventArgs e)
{
            System.Drawing.Icon ico = new Icon("sample.ico");
            Graphics graph = CreateGraphics();
            graph.DrawIcon(ico, new Rectangle(10, 10, 42, 42));
}

The second version allows you to specify only the location of the icon.

Practical Learning Practical Learning: Using an Icon

  1. Display the form and double-click the middle of its body
  2. To display the icon in the title bar, implement the event as follows:
     
    private void Form1_Load(object sender, EventArgs e)
    {
        System.Drawing.Icon icoMain = new System.Drawing.Icon("diamond.ico");
        Icon = icoMain;
    }
  3. Execute the application
     
  4. Close the form and return to your programming environment

A Cursor

 

Introduction

A cursor is a small picture that represents the position of the mouse on a Windows screen. Because Microsoft Windows is a graphic-oriented operating system, when it installs, it creates a set of standard or regularly used icons. These can be seen by opening the Control Panel window and double-clicking the Mouse icon. This opens the Mouse Properties dialog box where you can click the Pointers tab to see a list of standard cursors installed by Windows:

Mouse Properties

Microsoft Visual Studio 2005 provides a rich collection of cursors you can easily use in your application. You can apply them to any control as you wish.

To support cursors, the .NET Framework provides two classes. One of the classes used for cursors is called Cursors. This sealed class mostly contains a list of available cursors as properties. Another technique consists of using a cursor not listed in the Properties window. A cursor is based on the Cursor class. Both the Cursors and the Cursor classes are defined in the System.Windows.Forms namespace that is part of the System.Windows.Forms.dll library.

Practical Learning Practical Learning: Introducing Cursors

  1. From the Common Controls section of the Toolbox, click the ListBox control ListBox and click the upper-left section of the form
  2. From the Containers section of the Toolbox, click the Panel control Panel and click the upper-right section of the form
  3. Once again, from the Common Controls section of the Toolbox, click the TreeView control TreeView and click the lower-left section of the form
  4. From the Common Controls section of the Toolbox, click the RichTextBox control RichTextBox and click the lower-right section of the form
     
    Cursor

Creating a Cursor

A cursor is primarily represented in Microsoft Windows as a (resource) file. This means that, to get a cursor, you can design one. Fortunately, Microsoft Windows and the .NET Framework provides many cursors ready to be used. Otherwise, you can create and design your own.

To create a cursor, you can use use Microsoft Visual Studio. To start, on the main menu, you can click Project -> Add New Item... In the Templates list, you can click Cursor File, give it a name, and click Add.

A cursor is a Windows file that has the extension .cur.

Practical Learning Practical Learning: Creating a Cursor

  1. On the main menu, you can click Project -> Add New Item...
  2. In the Templates list, click Cursor File
  3. Change the Filename to push and click Add
  4. On the main menu, click File -> Save push.cur As...
  5. Locate and display the bin sub-folder of your project
  6. Double-click Debug to select that folder
  7. Click Save
  8. On the Image Editor toolbar, click the Line tool Line. In the Colors window, make sure the black color is selected
  9. Draw a vertical line from the pixel on the 6th column and 2nd row from top
  10. Draw a diagonal line at 45˚ from the top border of the new line to the lower-right until the line is at 5 pixels from the right border of the drawing area
     
    Cursor Design
  11. Draw a horizontal line from the lower border of the dialog line to half-left
  12. Draw a diagonal line from the lower border of the vertical line to the left border of the horizontal line:
     
    Cursor Design 2
  13. Draw another diagonal line from the top corner of the current shape to the intersection of horizontal and left diagonal line:
     
    Cursor Design 3
  14. On the Image Editor toolbar, click Fill Fill
  15. In the Colors window, click the button with a pink monitor
  16. In the drawing area, click the right triangle.
  17. In the Colors window, click the white color
  18. On the drawing area, click in the left triangle
     
    Cursor Design 4
  19. Save the file

Characteristics of a Cursor

 

Accessing a Cursor

There are two main ways you can use a cursor in your application. The easiest cursors are listed in the Cursor field of the Properties window for the control whose cursor you want to change. The available cursors are:

Cursor 1 Cursor 2 Cursor 3 Cursor 4

You can select one of these cursors in the Properties window and assign it to a control. These cursors are defined in a class called Cursors. This simple class mostly contains only a list of available cursors as properties. All these cursors are represented as static properties. Therefore, to use one of these cursors, call the name of the class, Cursors, followed by the class access operator ".", followed by the name of the cursor as it appears in the above list.

The Cursor class provides four constructors. One of them allows you to specify the path where the cursor is located. This constructor has the following syntax:

public Cursor(String filename);

The argument passed to this constructor is the name or the location of the cursor as a file. After calling this constructor to initialize a Cursor variable, the cursor is ready. You can then use it as you see fit. For example, you can assign it to the Cursor property of a control.

When the cursor of a control has been changed, the control fires a CursorChanged event. This event is of type EventArgs.

Practical Learning Practical Learning: Using Cursors

  1. Display the form. Click the control on the upper-left section of the form
  2. In the Properties window, click the arrow of the combo box of the Cursor field and select PanNorth
  3. Double-click an unoccupied area of the form to access its Load event
  4. To programmatically assign cursors, implement the event as follows:
     
    private void Form1_Load(object sender, EventArgs e)
    {
        System.Drawing.Icon icoMain = new System.Drawing.Icon("diamond.ico");
        Icon = icoMain;
    
        System.Windows.Forms.Cursor curPush = 
    		new System.Windows.Forms.Cursor("push.cur");
        panel1.Cursor = Cursors.NoMove2D;
        treeView1.Cursor = curPush;
        richTextBox1.Cursor = Cursors.PanSE;
    }
  5. Execute the application to test it
     
    Cursor Cursor on a control
    Control showing a cursor Cursor displaying
  6. Close the form and return to your programming environment

The Hot Spot of a Cursor

Besides showing the current position of the mouse, depending on the application, at one time, the user may need to click. Because a cursor is primarily confined to a rectangular shape, a cursor must specify which one of its sections would lead the clicking. The area that directs or holds the clicking on a cursor is referred to as its hot spot. The person who designs a cursor must also specify its hot spot. This means that the hot spots have already been specified for all the built-in cursors of Microsoft Windows and the cursor that ship with the .NET Framework.

If you are visually creating a cursor, to specify its hot spot, on the Image Editor toolbar, you can click the Set Hot Spot Set Hot Spot Tool. Then, on the cursor, click the point that will act as the hot spot.

On an existing cursor, to know the coordinates of the hot spot, access the value of its HotSpot property. The Cursor.HotSpot property is of type Point.

Practical Learning Practical Learning: Creating a Hot Spot for a Cursor

  1. Display the cursor you were designing
  2. To set the position of the cursor pointer, on the Image Editor toolbar, click the Set Hot Spot Tool Set Hot Spot Tool
  3. Click the tip of the cursor at the intersection of vertical and the the diagonal lines in the top-left section
     
    Set Hot Spot Tool
  4. Save and close the cursor window
  5. On the form, click an unoccupied area of the form
  6. In the Properties window, click the Events button and double-click the box right to MouseMove
  7. Implement the event as follows:
     
    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
                Text = "Hot Spot: F(" +
                           Cursor.HotSpot.X.ToString() +
                           ", " + Cursor.HotSpot.Y +
                           ")";
    }
  8. Return to the form
  9. Click the control on the top-left area of the form
  10. In the Events section of the Properties window, double-click the box right to MouseMove
  11. Implement the event as follows:
     
    private void listBox1_MouseMove(object sender, MouseEventArgs e)
    {
                Text = "Hot Spot: L(" +
                           listBox1.Cursor.HotSpot.X.ToString() +
                           ", " + listBox1.Cursor.HotSpot.Y +
                           ")";
    }
  12. Return to the form
  13. Click the control on the top-right area of the form
  14. In the Events section of the Properties window, double-click the box right to MouseMove
  15. Implement the event as follows:
     
    private void panel1_MouseMove(object sender, MouseEventArgs e)
    {
                Text = "Hot Spot: P(" +
                           panel1.Cursor.HotSpot.X.ToString() +
                           ", " + panel1.Cursor.HotSpot.Y +
                           ")";
    }
  16. Return to the form
  17. Click the control on the lower-left area of the form
  18. In the Events section of the Properties window, double-click the box right to MouseMove
  19. Implement the event as follows:
     
    private void treeView1_MouseMove(object sender, MouseEventArgs e)
    {
                Text = "Hot Spot: T(" +
                       treeView1.Cursor.HotSpot.X.ToString() +
                       ", " + treeView1.Cursor.HotSpot.Y +
                       ")";
    }
  20. Return to the form
  21. Click the control on the lower-right area of the form
  22. In the Events section of the Properties window, double-click the box right to MouseMove
  23. Implement the event as follows:
     
    private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
    {
                Text = "Hot Spot: R(" +
                       richTextBox1.Cursor.HotSpot.X.ToString() +
                       ", " + richTextBox1.Cursor.HotSpot.Y +
                       ")";
    }
  24. Execute the application to see the results:
     
  25. Close the form and return to your programming environment

The Size of a Cursor

A cursor is a picture of size 32 x 32 pixels. To know the size of an existing cursor, you can get the value of the Size property of the Cursor object. The Cursor.Size property is of type Size.

To specify the rectangle in which the cursor much be confined, you can create a Rectangle object and assign it to the Clip property of a cursor. To know the rectangle in which a cursor is confined, get the value of its Clip property. The Cursor.Clip property is of type Rectanble.

The Position of a Cursor

While the user is moving the mouse on a control, the cursor moves also, which, by its purpose, is designed to show the current position of the mouse. In some application, at one particular time, you may want to know the coordinates of the mouse position. To provide you with this information, the Cursor class is equipped with a property named Position. The Position property is of type Point, which gives you to left (X) and the top (Y) coordinates of the mouse. Here is an example that displays the position of the mouse on the title bar of a form:

private void Exercise_MouseMove(object sender, MouseEventArgs e)
{
            Text = Cursor.Position.X.ToString() +
                   ", " +
                   Cursor.Position.Y.ToString();
}

Showing or Hiding a Cursor

If at any time you want to hide a cursor, you can call the Cursor.Hide() method. Its syntax is:

public static void Hide();

To display the cursor again, you can call the Cursor.Show() method. Its syntax is:

public static void Show();

Exercises

 

Drawer

  1. Create an application named Drawer
  2. Configure it as follows:
    1. The default cursor of the form is Default
    2. If/when the user is simply/regularly moving the mouse on the form, the default cursor is Default
    3. If the user clicks the body of the form, holds down the mouse and starts dragging, the cursor becomes Cross
 
 

Previous Copyright © 2008-2009, yevol.com Next