Colors C# Help

This section discusses the ways that you can specify what color you want something to be drawn in.

Colors in GDI+ are represented by instances of the System, Drawing Color struct, Generally, once you have instantiated this struct, you won’t do much with the corresponding Color instance – you just pass it to whatever other method you are calling that requires a Color, You have encountered this struct before, when you set the background color of the client area of the window in each of the examples, (IS well as when you set the colors of the various shapes you were displaying, The Form Back Color property actually returns a Color instance, This section looks at this struct in more detail, In particular, it examines several different ways that you can construct a color.

Red-Green-Blue Values

The total number of colors that can be displayed by a monitor is huge – more than 16million, To be exact, the number is 2 to the power 24,which works out to 16,777,216.Obviously, you need some way of indexing those colors so that you can indicate which one is the color you want to display at any given pixel.

The most common way of indexing colors is by dividing them into the red, green, and blue components, This idea is based on the theory that any color that the human eye can distinguish can be constructed from a certain amount of red light, a certain amount of green light, and a certain amount of blue light, These colors are known as components, In practice, dividing the amount of each component light into 256 possible intensities yields a sufficiently fine gradation to be able to display images that are perceived by the human eye to be of photographic quality, You therefore, specify colors by giving the amounts of these components on a scale of 0 to 255 where 0 means that the component is not present and 255 means that it is at its maximum intensity.

This gives you your first way of telling GDI+ about a color. You can indicate a color’s red, green, and blue values by calling the static function Color, From Argb (), Microsoft has chosen not to supply a constructor to do this task. The reason is that there are other ways, besides the usual RGB components, to indicate a color. Because of this, Microsoft felt that the meaning of parameters passed to any constructor they defined would be open to misinterpretation:

Color redColor = Color.FromArgb(255,0,0);
Color funnyOrangyBrownColor = Color.FromArgb(255,155,100);
Color blackColor = Color.FromArgb(0,0,0);
Color whiteColor = color.FrOmArgb(255,255.255)~

The three parameters are, respectively, the quantities cf red, green, and blue, This function has a number of other overloads, some of which also allow you to specify something called an alpha-blend (that is the A in the name of the method, From Argb ()), Alpha blending is beyond, but it allows you to paint a color semi transparently by combining it with whatever color was already on the screen. This can give some beautiful effects and is often used in games.

The Named Colors

Constructing a Color using From Argb () is the most flexible technique because it literally means you can specify any color that the human eye can see, However, if you want a simple, standard, well-known color such as red or blue, it is a lot easier to just be able to name the color you want, Hence, Microsoft has also provided a large number of static properties in Color, each of which returns a named color, It was one of these properties that you used when you set the background color of your windows to white in the examples:

this.BackColor = Color.White;
// has the same effect as:
// this.BackColor = Color.FromArgb(255, 255, 255);

Several hundred such colors exist. The full list is given in the SDK documentation. They include all the simple colors: Red,white,Blue, Green, Black, and so on, as well as such delights as MediumAquamarine, LightCoral, and DarkOrchid, There is also a Known Color enumeration, which lists the named colors.

Each of these named colors represents a precise set of RGB values, They were originally chosen many years ago for use on the Internet, The idea was to provide a useful set of colors right across the spectrum whose names would be recognized by Web browsers, thus saving you from having to write explicit RGB values in your HTML code. A few years ago, these colors were also important because early browsers could not necessarily display very many colors accurately, and the named colors were supposed to provide a set of colors that would be displayed correctly by most browsers. These days, that aspect is less important because modern Web browsers are quite capable of displaying any RGB value correctly, Web-safe color palettes are also available that provide developers with a comprehensive list of colors that, work with most browsers.

Graphics Display Modes and the Safety Palette

Although in principle monitors can display any of the more than 16 million RGB colors, in practice this depends on how you have set the display properties on your computer. In Windows, there are traditionally three main color options (although some machines might provide other options depending on the hardware): true color (24 bit), high color (16 bit), and 256 colors. (On some graphics cards these days, true color is actually marked as 32 bit, This has to do with optimizing the hardware, though in that case only 24 bits of the 32 bits are used for the color itself.)

Only true color mode allows you to display all of the RGB colors simultaneously, This sounds like the best option, but it comes at a cost 3 bytes are needed to hold a full RGB value, which means that 3 bytes of graphics card memory are needed to hold each pixel that is displayed. If graphics card memory is at a premium (a restriction that is less common now than it used to be), then you might want to choose one of
the other modes, High color mode gives you 2 bytes per pixel, which is enough to give 5 bits for each RGB component, Therefore, instead of 256 gradations of red intensity, you get just 32 gradations, The same applies to blue and green,which produce a total of 65,536 colors, That is just about enough to give apparent photographic quality on a casual inspection, although areas of subtle shading tend to be broken up a bit.

The 256-color mode gives you even fewer colors. However, in this mode, you get to choose the colors, The system sets up something known as a palette. This is a list of 256 colors chosen from the 16 million RGB colors, Once you have specified the colors in the palette, the graphics device will be able to display just those colors, The palette can be changed at any time, but the graphics device can only display 256 different colors on the screen at anyone time, The 256-color mode is used only when high performances necessary and video memory is at a premium, Most computer games use this mode, They can still achieve decent-looking graphics because of a very careful choice of palette.

In general, if a display device is in high-color or 256-color mode and a particular RGB color is requested, then it will pick the nearest mathematical match from the pool of colors that it is able to display, It is for this reason that it is important to be aware of the color modes, If you are drawing something that involves subtle shading or photographic-quality images, and the user does not have 24-bit color mode selected, she might not see the image the same way you intended it, So if you are doing that kind of work with GDI+, then you should test your application in different color modes, (It is also possible for your application to programmatically set a given color mode.

The Safety Palette

For reference, this section quickly mentions the safety palette, which is a very commonly used default palette, To use the safety palette, you set six equally spaced possible values for each color component: 0, 51,102,153,204, and 255, In other words, the red component can have any of these values, The green component can have any of these values and so can the blue component. Possible colors from the safety palette include (0,0,0),black; (153,0,0),a fairly dark shade of red; (0, 255,102),green with a smattering of blue added; and so on. This gives you a total of 6 cubed = 216 colors, The idea is that this provides an easy way of creating a palette that contains colors from right across the spectrum and of all degrees of brightness, In practice however, this does not actually work that well because equal mathematical spacing of color components does not mean equal perception of color differences by the human eye.

If you set Windows to 256-color mode, you will find that the default palette is the safety palette, with 20 Windows-standard colors added to it, and 20 spare colors.

Pens and Brushes

This section reviews two helper classes that are needed to draw shapes, You have already encountered the Pen class, which you used to instruct the graphics instance how to draw lines, A related class is System, Drawing, Brush, which instructs the graphics instance how to fill regions. For example, the Pen is needed to draw, the outlines of the rectangle and ellipse in the previous examples, If you had needed to draw these shapes as solid, you would have used a brush to specify how to fill them, One aspect of both of these classes is that you will hardly ever call any methods on them, You simply construct a Pen or Brush instance with the required color and other properties, and then pass it to drawing methods that require a Pen or Brush.

all drawing operations that required a pen until you informed the device context otherwise, by calling Select Object () again, The same principle held for brushes all other objects such as fonts or bitmaps, With GDI+, Microsoft has opted for a stateless model ill which there is no default pen or other helper object, Rather, you simply specify with each method call the appropriate helper object to be used for that particular method.


GDI+ has several different kinds of brushes – more than there is space, so this section just explains the simpler ones to give you an idea of the principles, Each type of brush is represented by an instance of a class derived from the abstract class System, Drawing Brush, The simplest brush, System Drawing, SolidBrush, indicates that a region is to be filled with solid color:

Brush SolidBeigebrush = new SolidBrush (color.Beige) ;
BrushsolidFunnyOrangyBrownBrush=new solidBrush(color.FromArgb(255,155,100));

Alternatively, if the brush is one of the Web-safe colors, then you can construct the brush using another class, System, Drawing Brushes, Brushes is one of those classes that you never actually instantiate (it has a private constructor to stop you from doing that), It simply has a large number of static properties, each of which returns a brush of a specified color. You can use Brushes like this:

Brush solidAzureBrush = Brushes.Azure;
Brush solidChocolateBrush = Brushes.Chocolate;

The next level of complexity is a hatch brush, which fills a region by drawing a pattern, This type of brush is considered more advanced, so it is in the Drawing2D namespace, represented by the class System, Drawing, Drawing2D HatchBrush,The Brushes class cannot help you with hatch brushes;

you will need to construct one explicitly by supplying the hatch style and two colors – the foreground color followed by the background color. (Note, you can omit the background color, in which case it defaults to black), The hatch style comes from an enumeration, System Drawing, Drawing2D HatchStyle You can choose from a large number of HatchStyle values (see the SDK documentation for the full list), To give you an idea, typical styles include Forward Diagonal, Cross, DiagonalCross, SmallConfetti, and ZigZag, Examples of constructing a hatch brush include:

Brush crossBrush = new HatchBrush(HatchStyle.Cross, Color.Azure);
// background color of CrQssBrush is black
Brush brickBrush = new HatchBrush(HatchStyle.DiagonalBrick,
Color.DarkGoldenrod, Color.Cyan);

Solid and hatch brushes are the only brushes available under GDI, GDI+ has added a couple of new styles of brushes:

  1. System. Drawing. Drawing2D. LinearGradientBrush fills in an area with a color that varies across the screen.
  2. System. Drawing Drawing2D, PathGradientBrush is similar, but in this case, the color varies along a path around the region to be filled.

Note that both brushes can render some spectacular effects if used carefully.


Unlike brushes, pens are represented by just one class: System. Drawing. Pen. However, the pen is slightly more complex than the brush because it needs to indicate how thick lines should be (how many pixels wide) and, for a wide line, how to fill the area inside the line. Pens can also specify a number of other properties, which are beyond the scope of this chapter, but which include the Alignment property mentioned earlier, This property indicates where in relation to the border of a shape a line should be drawn, as well as what shape to draw at the end of a line (whether to round off the shape).

The area inside a thick line can be filled with solid color or by using a brush, Hence a Pen instance might contain a reference to a Brush instance, This is quite powerful because it means that you can draw lines that are colored in by using, say hatching or linear shading, There are four different ways to construct a Pen instance that you have designed yourself, One is by passing a color; a second is by passing in a brush, Both of these constructors will produce a pen with a width of one pixel, Alternatively a third way is to pass in a color or a brush, and additionally a float, which represents the width of the pen, (It needs to be a float in case you are using non-default units such as millimeters or inches for the Graphics object that will do the drawing, so you can, for example, specify fractions of an inch) For example, you can construct pens like this:

Additionally, a fourth way offers the quick construction of pens by using the class System, Drawing Pens, which, like the Brushes class, contains a number of stock pens, These pens all have a 1-pixel width and come in the usual sets of Web-safe colors. This allows you to construct pens in this way:

Pen solidYellowPen = Pens.Yellow;

Posted on November 3, 2015 in Graphics with GDI+

Share the Story

Back to Top
Share This