Color Control
Colors can enhance a program's appearance and help convey meaning. For example, a red traffic light indicates stop, yellow indicates caution and green indicates go. Structure Color defines methods and constants used to manipulate colors.
Every color can be created from a combination of alpha, red, green and blue components (called ARGB values). All four ARGB components are bytes that represent integer values in the range 0 to 255. The alpha value determines the opacity of the color. For example, the alpha value 0 represents a transparent color, and the value 255 represents an opaque color. Alpha values between 0 and 255 result in a weighted blending effect of the color's RGB value with that of any background color, causing a semitransparent effect. The first number in the RGB value defines the amount of red in the color, the second defines the amount of green and the third defines the amount of blue. The larger the value, the greater the amount of that particular color. C# enables programmers to choose from almost 17 million colors. If a particular computer cannot display all these colors, it will display the color closest to the one specified. Figure 17.3 summarizes some predefined Color constants (all are public and static), and Fig. 17.4 describes several Color methods and properties. For a complete list of predefined Color constants, methods and properties, see the online documentation for the Color structure (msdn2.microsoft.com/en-us/library/system.drawing.color).
Constants in structure Color |
RGB value |
---|---|
Orange |
255, 200, 0 |
Pink |
255, 175, 175 |
Cyan |
0, 255, 255 |
Magenta |
255, 0, 255 |
Yellow |
255, 255, 0 |
Black |
0, 0, 0 |
White |
255, 255, 255 |
Gray |
128, 128, 128 |
DarkGray |
64, 64, 64 |
Red |
255, 0, 0 |
Green |
0, 255, 0 |
Blue |
0, 0, 255 |
Structure Color methods and properties |
Description |
---|---|
Common Methods |
|
FromArgb |
A static method that creates a color based on red, green and blue values expressed as ints from 0 to 255. The overloaded version allows specification of alpha, red, green and blue values. |
FromName |
A static method that creates a color from a name, passed as a string. |
Common Properties |
|
A |
A byte between 0 and 255, representing the alpha component. |
R |
A byte between 0 and 255, representing the red component. |
G |
A byte between 0 and 255, representing the green component. |
B |
A byte between 0 and 255, representing the blue component. |
The table in Fig. 17.4 describes two FromArgb method calls. One takes three int arguments, and one takes four int arguments (all argument values must be between 0 and 255, inclusive). Both take int arguments specifying the amount of red, green and blue. The overloaded version also allows the user to specify the alpha component; the three-argument version defaults the alpha to 255 (opaque). Both methods return a Color object. Color properties A, R, G and B return bytes that represent int values from 0 to 255, corresponding to the amounts of alpha, red, green and blue, respectively.
Programmers draw shapes and strings with Brushes and Pens. A Pen, which functions similarly to an ordinary pen, is used to draw lines. Most drawing methods require a Pen object. The overloaded Pen constructors allow programmers to specify the colors and widths of the lines that they wish to draw. The System.Drawing namespace also provides a Pens class containing predefined Pens.
All classes derived from abstract class Brush define objects that color the interiors of graphical shapes. For example, the SolidBrush constructor takes a Color objectthe color to draw. In most Fill methods, Brushes fill a space with a color, pattern or image. Figure 17.5 summarizes various Brushes and their functions.
Class |
Description |
---|---|
HatchBrush |
Fills a region with a pattern. The pattern is defined by a member of the HatchStyle enumeration, a foreground color (with which the pattern is drawn) and a background color. |
LinearGradientBrush |
Fills a region with a gradual blend of one color to another. Linear gradients are defined along a line. They can be specified by the two colors, the angle of the gradient and either the width of a rectangle or two points. |
SolidBrush |
Fills a region with one color that is specified by a Color object. |
TextureBrush |
Fills a region by repeating a specified Image across the surface. |
Manipulating Colors
Figure 17.6 demonstrates several of the methods and properties described in Fig. 17.4. It displays two overlapping rectangles, allowing you to experiment with color values, color names and alpha values (for transparency).
Figure 17.6. Color value and alpha demonstration.
1 // Fig 17.6: ShowColors.cs 2 // Color value and alpha demonstration. 3 using System; 4 using System.Drawing; 5 using System.Windows.Forms; 6 7 public partial class ShowColors : Form 8 { 9 // color for back rectangle 10 private Color backColor = Color.Wheat; 11 12 // color for front rectangle 13 private Color frontColor = Color.FromArgb( 100, 0, 0, 255 ); 14 15 // default constructor 16 public ShowColors() 17 { 18 InitializeComponent(); 19 } // end constructor 20 21 // override Form OnPaint method 22 protected override void OnPaint( PaintEventArgs e ) 23 { 24 Graphics graphicsObject = e.Graphics; // get graphics 25 26 // create text brush 27 SolidBrush textBrush = new SolidBrush( Color.Black ); 28 29 // create solid brush 30 SolidBrush brush = new SolidBrush( Color.White ); 31 32 // draw white background 33 graphicsObject.FillRectangle( brush, 4, 4, 275, 180 ); 34 35 // display name of backColor 36 graphicsObject.DrawString( backColor.Name, this.Font, 37 textBrush, 40, 5 ); 38 39 // set brush color and display back rectangle 40 brush.Color = backColor; 41 graphicsObject.FillRectangle( brush, 45, 20, 150, 120 ); 42 43 // display Argb values of front color 44 graphicsObject.DrawString( "Alpha: " + frontColor.A + 45 " Red: " + frontColor.R + " Green: " + frontColor.G + 46 " Blue: " + frontColor.B, this.Font, textBrush, 55, 165 ); 47 48 // set brush color and display front rectangle 49 brush.Color = frontColor; 50 graphicsObject.FillRectangle( brush, 65, 35, 170, 130 ); 51 } // end method OnPaint 52 53 // handle colorNameButton click event 54 private void colorNameButton_Click( object sender, EventArgs e ) 55 { 56 // set backColor to color specified in text box 57 backColor = Color.FromName( colorNameTextBox.Text ); 58 59 Invalidate(); // refresh Form 60 } // end method colorNameButton_Click 61 62 // handle colorValueButton click event 63 private void colorValueButton_Click( object sender, EventArgs e ) 64 { 65 // obtain new front color from text boxes 66 frontColor = Color.FromArgb( 67 Convert.ToInt32( alphaTextBox.Text ), 68 Convert.ToInt32( redTextBox.Text ), 69 Convert.ToInt32( greenTextBox.Text ), 70 Convert.ToInt32( blueTextBox.Text ) ); 71 72 Invalidate(); // refresh Form 73 } // end method colorValueButton_Click 74 } // end class ShowColors |
When the application begins executing, its Form is displayed. This results in a call to ShowColors's OnPaint method to paint the Form's contents. Line 24 gets a reference to PaintEventArgs e's Graphics object and assigns it to graphicsObject. Lines 27 and 30 create a black and a white SolidBrush for drawing solid shapes on the Form. Class SolidBrush derives from abstract base class Brush, so a SolidBrush can be passed to any method that expects a Brush parameter.
Line 33 uses Graphics method FillRectangle to draw a solid white rectangle using the SolidBrush created in line 30. FillRectangle takes as parameters a Brush, the x- and y-coordinates of the rectangle's upper-left corner, and the width and height of the rectangle. Lines 3637 display the Name property of backColor with Graphics method DrawString. There are several overloaded DrawString methods; the version demonstrated in lines 3637 takes as arguments the string to display, the display Font, the Brush to use for drawing and the x- and y-coordinates of the location for the string's first character.
Lines 4041 assign the backColor value to brush's Color property and display a rectangle. Lines 4446 extract and display frontColor's ARGB values and draw a string containing those values. Lines 4950 assign the frontColor value to brush's Color property, then draw a filled rectangle in the frontColor that overlaps the rectangle drawn at line 41.
Button event handler colorNameButton_Click (lines 5460) uses class Color's static method FromName to create a new Color object from the colorName that a user enters in a TextBox. This Color is assigned to backColor (line 57). Then line 59 invokes the Form's Invalidate method to indicate that the Form should be repainted, which results in a call to OnPaint to update the Form on the screen.
Button event handler colorValueButton_Click (lines 6373) uses Color method FromArgb to construct a new Color object from the ARGB values that a user specifies via TextBoxes, then assigns the newly created Color to frontColor. Line 72 invokes the Form's Invalidate method to indicate that the Form should be repainted, which results in a call to OnPaint to update the Form on the screen.
If the user assigns an alpha value between 0 and 255 for the frontColor, the effects of alpha blending are apparent. In the sample output, the red back rectangle blends with the blue front rectangle to create purple where the two overlap. Note that you cannot change the characteristics of an existing Color object. To use a different color, create a new Color object.
Using the ColorDialog to Select Colors from a Color Palette
The predefined GUI component ColorDialog is a dialog box that allows users to select from a palette of available colors or to create custom colors. Figure 17.7 demonstrates the ColorDialog. When a user selects a color and presses OK, the application retrieves the user's selection via the ColorDialog's Color property.
Figure 17.7. ColorDialog used to change background and text color.
1 // Fig. 17.7: ShowColorsComplex.cs
2 // ColorDialog used to change background and text color.
3 using System;
4 using System.Drawing;
5 using System.Windows.Forms;
6
7 // allows users to change colors using a ColorDialog
8 public partial class ShowColorsComplex : Form
9 {
10 // create ColorDialog object
11 private static ColorDialog colorChooser = new ColorDialog();
12
13 // default constructor
14 public ShowColorsComplex()
15 {
16 InitializeComponent();
17 } // end constructor
18
19 // change text color
20 private void textColorButton_Click( object sender, EventArgs e )
21 {
22 // get chosen color
23 DialogResult result = colorChooser.ShowDialog();
24
25 if ( result == DialogResult.Cancel )
26 return;
27
28 // assign forecolor to result of dialog 29 backgroundColorButton.ForeColor = colorChooser.Color; 30 textColorButton.ForeColor = colorChooser.Color; 31 } // end method textColorButton_Click 32 33 // change background color 34 private void backgroundColorButton_Click( object sender, EventArgs e ) 35 { 36 // show ColorDialog and get result 37 colorChooser.FullOpen = true; 38 DialogResult result = colorChooser.ShowDialog(); 39 40 if ( result == DialogResult.Cancel ) 41 return; 42 43 // set background color 44 this.BackColor = colorChooser.Color; 45 } // end method backgroundColorButton_Click 46 } // end class ShowColorsComplex
|
The GUI for this application contains two Buttons. The backgroundColorButton allows the user to change the form background color. The textColorButton allows the user to change the button text colors. Line 11 creates a private static ColorDialog named colorChooser, which is used in the event handlers for both Buttons.
Lines 2031 define the textColorButtonClick event handler, which invokes colorChooser's ShowDialog method (line 23) to display the dialog. The dialog's Color property stores the user's selection. Lines 2930 set the text color of both buttons to the selected color.
Lines 3445 define the backgroundColorButtonClick event handler, which modifies the background color of the form by setting its BackColor property to the dialog's Color property (line 44). The method sets the ColorDialog's FullOpen property to TRue (line 37), so the dialog displays all available colors, as shown in the screen capture in Fig. 17.7. When FullOpen is false, the dialog shows only the color swatches.
Users are not restricted to the ColorDialog's 48 color swatches. To create a custom color, users can click anywhere in the ColorDialog's large rectangle, which displays various color shades. Adjust the slider, hue and other features to refine the color. When finished, click the Add to Custom Colors button, which adds the custom color to a square in the Custom Colors section of the dialog. Clicking OK sets the Color property of the ColorDialog to that color.