Reader Level:
ARTICLE

Use System Brushes and Pens in GDI+

Posted by Dinesh Beniwal Articles | GDI+ & Graphics July 16, 2010
In this article you will learn how to use System Brushes and Pens in GDI+.
  • 0
  • 0
  • 6265
Download Files:
 

This article has been excerpted from book "Graphics Programming with GDI+".

You can always create system pens and system brushes with system colors by using the SystemColors class, but for performance reason it is advisable to use SystemPens and SystemBrushes instead of SystemColors. For example, the following code creates SolidBrush and Pen objects using SystemColors. The brush and pen have the ActiveCaption and ControlDarkDark system colors, respectively.

            SolidBrush brush =
(SolidBrush)SystemBrushes.FormsSystemColor
(SystemColors.ActiveCaption);
            Pen pn = SystemPens.FromStystemColor
            (systemColors.ControlDarkDark);

We can create the same brush and pen using the static methods of SystemBrushes and SystemPens, as the following code snippet illustrates:

            SolidBrush brush =
            (SolidBrush)SystemBrushes.ActiveCaption;
            Pen pn = SystemPens.ControlDarkDark;

Never dispose of system pens and brushes. Any attempt to do so will result in an unhandled exception. For example, adding the following two lines to the code will throw an exception:

pn.Dispose();
brush.Dispose();

Listing 13.15 shows the complete code of a form's paint event handler.

LISTING 13.15: Using system pens and brushes

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            //AVOID
            /* SolidBrush brush =
            (SolidBrush) SystemBrushes.FromSystemColor
            (SystemColors.ActiveCaption);
            */
            SolidBrush brush =
            (SolidBrush)SystemBrushes.ActiveCaption;
            Pen pn = SystemPens.ControlDarkDark;
            g.DrawLine(pn, 20, 20, 20, 100);
            g.DrawLine(pn, 20, 20, 100, 20);
            g.FillRectangle(brush, 30, 30, 50, 50);
            //Don't
            //pn.Dispose();
            //brush.Dispose();
        }

Figure 13.7 shows the output from Listing 13.5. The lines and rectangle are drawn with system colors.

Avoid Automatic Scaling of Images

Automatic scaling could result in performance degradation. If possible, avoid automatic scaling. The DrawImage method takes a Bitmap object and a rectangle with upper left corner position and specified width and height. If we pass only the upper left corner position, GDI+ may scale the image, which decreases performance. For example, the code

e.Graphics.DrawImage (image, 10, 10);

can be replaced with the following code:

e.Graphics.DrawImage (image, 10, 10, image.Width, image.Height);

Figure 13.7.gif

FIGURE 13.7: Using system pens and brushes

Book.jpg

COMMENT USING

Trending up