Introduction to GDI


Introduction to GDI+

GDI+ is the graphics library responsible for all graphics rendering within the .NET Framework. You can use GDI+ to draw lines and shapes, fill shapes with solid colors or gradients, perform simple animation, or even manipulate existing images found on disk or retrieved from the web.

All GDI+ rendering is done on a special GDI+ surface. These surfaces can be a Windows Form or the contained area within a control. The GDI+ surface is represented by the Graphics object in the System.Drawing namespace. When you are drawing lines and shapes or performing fill operations, they will all be done against a Graphics object.

You can create a Graphics object in one of three different ways:

  • Obtain an instance of the Graphics class from the PaintEventArgs argument in the Paint event of a form or a control. This is fairly common when you are overriding the default paint routine of a form or a control.

  • Use the CreateGraphics method of a form or a control to return an instance of the Graphics class that encapsulates the drawing surface represented by that form or control.

  • Create an instance of Graphics from any object that inherits from the Image class. This technique is used quite often when using GDI+ to manipulate existing images.

Obtaining a Graphics Object

To obtain a reference to the Graphics object using CreateGraphics, create a new Windows Forms application and drag a button onto the default form. Then, set the event handler for that button's Click event to the following lines of code:

private void button1_Click(object sender, EventArgs e) { using (Graphics g = this.CreateGraphics()) {     using (Pen p = new Pen(Color.Purple))     {         g.DrawLine(p, new Point(1, 1), new Point(this.Width, this.Height));     } } } 


This code will draw a line from the top left of the form to the bottom right of the form using a purple line. In order to draw anything in GDI+, you must have a pen. The pen defines the style of what you are drawing. You can either create a Pen instance based on a color as shown in the preceding code or you can create a Pen from a custom brush such as a LinearGradientBrush (discussed in the "Using a Gradient Brush" section). Figure 36.1 shows the line drawn by the preceding code.

Figure 36.1. Drawing a line.


Creating a "Hello GDI+" Sample

In addition to drawing lines using GDI+, you can also draw text. The Graphics class contains a DrawString method that can be used to place text on a drawing surface such as a form or a control. When you draw the text, you must specify the text font, a brush to use when drawing the text (using custom brushes while drawing text can create some very interesting effects such as gradient-filled letters), and the location where the text will appear, as shown in the following code:

private void button2_Click(object sender, EventArgs e) {     string text = "Hello GDI+";     using (Graphics g = this.CreateGraphics())     {         using (Font textFont = new Font("Agency FB", 18))         {             using (SolidBrush textBrush = new SolidBrush(Color.DarkRed))             {                 StringFormat drawFormat = new StringFormat();                 g.DrawString(text, textFont, textBrush, 1.0f, 1.0f, drawFormat);             }         }     } } 


After running this sample with the button1 that you created previously still in place, you get output that has a diagonal line on the form and some colored text in the top-left corner of the form, as shown in Figure 36.2.

Figure 36.2. Drawing lines and text.


You might notice that anything you draw in response to a button click will quickly disappear if your form needs to repaint itself. This is because when the form repaints it doesn't know that it needs to draw the line or the text. An important lesson to learn in GDI+ programming is when you should use a Paint event and when you shouldn't. To see how this all fits together, add the following lines of code to the sample you've been working with:

protected override void OnPaint(PaintEventArgs e) {     base.OnPaint(e);     using (Graphics g = this.CreateGraphics())     {         using (Font textFont = new Font("Arial", 18))         {             using (SolidBrush textBrush = new SolidBrush(Color.Black))             {                 g.DrawString("Always Painted", textFont, textBrush, 1.0f, (float)this.Height / 2);             }         }     } } 


Now run the sample. You'll see that the phrase "Always Painted" shows up immediately. If you click the Draw Line and Draw Text buttons, you should see all of the graphics. Minimize the window and then restore it. The diagonal line and the "Hello GDI+" phrase have disappeared because the form repainted, erasing all previously rendered graphics. After the form repaint, using the OnPaint overridden method, the form redrew the "Always Painted" text. This gives the impression to the end user that the phrase "Always Painted" never disappeared.

Drawing and Filling Shapes

The next sample will show you how to use pens and solid brushes to create hollow and filled shapes using the Graphics class. Start by creating a new Windows Forms application. Add four buttons to the form: Create Hollow Rectangle, Create Filled Rectangle, Create Hollow Ellipse, and Create Filled Ellipse. In this sample the names of the buttons are left as button1 tHRough button4 respectively. Finally, add a button labeled "Clear Image" to the bottom. Next, add a PictureBox control to the form.

The code in Listing 36.1 shows all of the event handlers for the various buttons, including the Clear Image button.

Listing 36.1. Drawing and Filling Shapes

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace GDIPlus2 { public partial class Form1 : Form { public Form1() {     InitializeComponent(); } // hollow rectangle private void button1_Click(object sender, EventArgs e) {     using (Graphics g = pictureBox1.CreateGraphics())     {         using (Pen p = new Pen(Color.Red))         {             g.DrawRectangle(p, 1.0f, 1.0f, pictureBox1.Width - 10, pictureBox1.Height - 10);         }     } } // clear image private void button5_Click(object sender, EventArgs e) {     pictureBox1.Image = null; } // filled rectangle private void button2_Click(object sender, EventArgs e) {     using (Graphics g = pictureBox1.CreateGraphics())     {         using (SolidBrush brush = new SolidBrush(Color.DarkOrchid))         {             g.FillRectangle(brush, 1.0f, 1.0f, pictureBox1.Width - 10, pictureBox1.Height - 10);         }     } } // hollow ellipse private void button3_Click(object sender, EventArgs e) {     using (Graphics g = pictureBox1.CreateGraphics())     {         using (Pen p = new Pen(Color.DarkBlue))         {             g.DrawEllipse(p, 1.0f, 1.0f, pictureBox1.Width - 10, pictureBox1.Height - 10);         }     } } // filled ellipse private void button4_Click(object sender, EventArgs e) {     using (Graphics g = pictureBox1.CreateGraphics())     {         using (SolidBrush b = new SolidBrush(Color.Brown))         {             g.FillEllipse(b, 1.0f, 1.0f, pictureBox1.Width - 10, pictureBox1.Height - 10);         }     } } } } 

Figure 36.3 shows this application in action. Notice that the order in which you click the drawing buttons has an impact on the type of image you see on the right. Each sequential drawing instruction will draw on top of the currently rendered surface. This means that if you draw a small circle and then draw a large square over the same area, the circle will disappear.

Figure 36.3. Drawing and filling shapes.


Remember that because these graphics were drawn in response to button clicks and not during the Paint event, they will disappear when the window is repainted.

Using a Gradient Brush

A gradient is a gradual transition from one color to another. This transition can also take place at any angle you choose, giving you an amazing number of choices when creating shading and color transition effects. Many user interface studies have shown that a subtle color transition for a control's background is far easier to look at than solid colors. This is why all of the toolbars in Office 2003 aren't solid backgrounds. They are actually vertical transitions from an aqua color to a light blue color.

The subtle application of gradient brushes to your application and your custom controls can do wonders for its look and feel. If used appropriately, they can make an ordinary application look far more professional.

To illustrate how to use gradient brushes, try rewriting the previous application. Everywhere that a SolidBrush was used, you can replace that code with the instantiation of a LinearGradientBrush. Listing 36.2 shows the new code that will replace solid fills with gradient fills.

Listing 36.2. Hollow Shapes and Gradient Fills

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing.Drawing2D; using System.Drawing; using System.Text; using System.Windows.Forms; namespace GDIPlus3 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button5_Click(object sender, EventArgs e) { pictureBox1.Image = null; } private void button1_Click(object sender, EventArgs e) { using (Graphics g = pictureBox1.CreateGraphics()) {     using (Pen p = new Pen(Color.Black))     {         g.DrawRectangle(p, 1.0f, 1.0f,             pictureBox1.Width - 10, pictureBox1.Height - 10);     } } } private void button2_Click(object sender, EventArgs e) { using (Graphics g = pictureBox1.CreateGraphics()) {     using (LinearGradientBrush lgb = new LinearGradientBrush(         new Rectangle(1, 1, pictureBox1.Width - 10, pictureBox1.Height - 1),         Color.Cyan, Color.Blue, 90))     {         g.FillRectangle(lgb, 1.0f, 1.0f, pictureBox1.Width - 10,             pictureBox1.Height - 10);     } } } private void button3_Click(object sender, EventArgs e) { using (Graphics g = pictureBox1.CreateGraphics()) {     using (Pen p = new Pen(Color.Black))     {         g.DrawEllipse(p, 1.0f, 1.0f,             pictureBox1.Width - 10,             pictureBox1.Height-10);     } } } private void button4_Click(object sender, EventArgs e) { using (Graphics g = pictureBox1.CreateGraphics()) {     using (LinearGradientBrush lgb = new LinearGradientBrush(         new Rectangle(1, 1, pictureBox1.Width - 10, pictureBox1.Height - 1),         Color.Orange, Color.Red, 90))     {         g.FillEllipse(lgb, 1.0f, 1.0f, pictureBox1.Width - 10,             pictureBox1.Height - 10);     } } } } } 

Run the sample and see how the new filled shapes have gradually shifting colors in them to form the gradient effect as shown in Figure 36.4. Experiment with changing the gradient's angle (it is 90 degrees in Listing 36.2) and the start and end colors to see the variety of effects you can create.

Figure 36.4. Gradient shape filling.




Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net