Section 17.4. Color Control


17.4. 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 color. Programmers can choose from almost 17 million colors. If a 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 Shared), and Fig. 17.4 describes several Color methods and properties. For a complete list of the predefined Color constants, methods and properties, see Color structure's online documentation (msdn2.microsoft.com/en-us/library/system.drawing.color).

Figure 17.3. Color structure Shared constants and their RGB values.

Constants in structure Color

RGB value

Constants in structure Color

RGB value

Orange

255, 200, 0

White

255, 255, 2 55

Pink

255, 175, 175

Gray

128, 128, 128

Cyan

0, 255, 2 55

DarkGray

64, 64, 64

Magenta

255, 0, 2 55

Red

255, 0, 0

Yellow

255, 255, 0

Green

0, 255, 0

Black

0, 0, 0

Blue

0, 0, 2 55


Figure 17.4. Color structure members.

Structure Color methods and properties

Description

Common Methods

FromArgb

A Shared 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 Shared 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 Integer arguments, and one takes four Integer arguments (all argument values must be between 0 and 255, inclusive). Both take Integer 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 Integer 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 they wish to draw. The System.Drawing namespace also provides a Pens class containing predefined Pens.

All classes derived from MustInherit 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.

Figure 17.5. Classes that derive from class Brush.

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: FrmShowColors.vb  2  ' Color value and alpha demonstration.  3  Public Class FrmShowColors  4     ' color for back rectangle  5     Private backgroundColor As Color = Color.Wheat  6  7     ' color for front rectangle  8     Private foregroundColor As Color = Color.FromArgb(100, 0, 0, 255)  9 10     ' override Form's OnPaint method 11     Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs) 12        Dim graphicsObject As Graphics = e.Graphics ' get graphics object 13 14        ' create text brush 15        Dim textBrush As New SolidBrush(Color.Black) 16 17        ' create solid brush 18        Dim brush As New SolidBrush(Color.White) 19 20        ' draw white background 21        graphicsObject.FillRectangle(brush, 4, 4, 27, 180) 22 23        ' display name of backColor 24        graphicsObject.DrawString( _                   25           BackColor.Name, Me.Font, textBrush, 40, 5) 26 27        ' set brush color and display back rectangle 28        brush.Color = backgroundColor                         29        graphicsObject.FillRectangle(brush, 45, 20, 150, 120) 30 31        ' display Argb values of front color 32        graphicsObject.DrawString("Alpha: " & foregroundColor.A & _       33           " Red: " & foregroundColor.R & " Green: " & _               34           foregroundColor.G & " Blue: " & foregroundColor.B, Me.Font, _ 35           textBrush, 55, 165)                                            36 37        ' set brush color and display front rectangle 38        brush.Color = foregroundColor                         39        graphicsObject.FillRectangle(brush, 65, 35, 170, 130) 40     End Sub ' OnPaint 41 42     ' change Form's background color 43     Private Sub btnColorName_Click(ByVal sender As System.Object, _ 44        ByVal e As System.EventArgs) Handles btnColorName.Click 45        ' set backColor to color specified in text box 46        backgroundColor = Color.FromName(txtColorName.Text) 47        Invalidate() ' refresh Form                         48     End Sub ' btnColorName_Click 49 50     ' change Form's foreground color 51     Private Sub btnColorValue_Click(ByVal sender As System.Object, _ 52        ByVal e As System.EventArgs) Handles btnColorValue.Click 53        ' obtain new front color from text boxes 54        foregroundColor = Color.FromArgb( _                                55           Convert.ToInt32(txtAlpha.Text), Convert.ToInt32(txtRed.Text), _ 56            Convert.ToInt32(txtGreen.Text), Convert.ToInt32(txtBlue.Text)) 57        Invalidate() ' refresh Form                                        58     End Sub ' btnColorValue_Click 59  End Class ' FrmShowColors 

When the application begins executing, its Form is displayed. This results in a call to FrmShowColors's OnPaint method to paint the Form's contents. Line 12 gets a reference to PaintEventArgs e's Graphics object and assigns it to graphicsObject. Lines 15 and 18 create a black and a white SolidBrush for drawing solid shapes on the Form. Class SolidBrush derives from MustInherit class Brush, so a SolidBrush can be passed to any method that expects a Brush parameter.

Line 21 uses Graphics method FillRectangle to draw a solid white rectangle using the SolidBrush created in line 18. 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 2425 display the Name property of BackColor with Graphics method Draw-String. There are several overloaded DrawString methods; the version demonstrated in lines 2425 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 2829 assign the backgroundColor value to brush's Color property and display a rectangle. Lines 3235 extract and display foregroundColor's ARGB values and draw a string containing those values. Lines 3839 assign the foregroundColor value to brush's Color property, then draw a filled rectangle in the foregroundColor that overlaps the rectangle drawn at line 29.

Button event handler btnColorName_Click (lines 4348) uses class Color's Shared method FromName to create a new Color object from the color name that a user enters in a TextBox. This Color is assigned to backgroundColor (line 46). Then line 47 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 btnColorValue_Click (lines 5158) uses Color method FromArgb to construct a new Color object from the ARGB values that a user specifies via Text-Boxes, then assigns the newly created Color to foregroundColor. Line 57 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.

Changing the alpha value of the foregroundColor from 0 to 255, makes the effects of alpha blending apparent. The sample output shows that the red back rectangle blends with the blue front rectangle to create purple where they overlap. Note that you cannot modify 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: FrmShowColorsComplex.vb  2  ' ColorDialog used to change background and text color.  3  Public Class FrmShowColorsComplex  4     ' create ColorDialog object  5     Private Shared colorChooser As New ColorDialog()  6  7     ' change background color  8     Private Sub btnBackgroundColor_Click(ByVal sender As System.Object, _  9        ByVal e As System.EventArgs) Handles btnBackgroundColor.Click 10        ' show ColorDialog and get result 11        colorChooser.FullOpen = True                           12        Dim result As DialogResult = colorChooser.ShowDialog() 13 14        If result = Windows.Forms.DialogResult.OK Then 15           Me.BackColor = colorChooser.Color ' set background color 16        End If 17     End Sub ' btnBackgroundColor_Click 18 19     ' change text color 20     Private Sub btnTextColor_Click(ByVal sender As System.Object, _ 21        ByVal e As System.EventArgs) Handles btnTextColor.Click 22        ' get chosen color 23        Dim result As DialogResult = colorChooser.ShowDialog() 24 25        If result = Windows.Forms.DialogResult.OK Then 26           ' assign forecolor to result of dialog 27           btnBackgroundColor.ForeColor = colorChooser.Color 28           btnTextColor.ForeColor = colorChooser.Color       29        End If 30     End Sub ' btnTextColor_Click 31  End Class ' FrmShowColorsComplex 

The GUI for this application contains two Buttons. The btnBackgroundColor allows the user to change the Form's background color. The btnTextColor allows the user to change the button text colors. Line 5 creates a Private Shared ColorDialog named colorChooser, which is used in the event handlers for both Buttons.

Lines 817 define the btnBackgroundColor_Click event handler. The method sets the ColorDialog's FullOpen property to true (line 11), 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. Line 12 invokes colorChooser's ShowDialog method to display the dialog. The dialog's Color property stores the user's selection. If the user clicks OK, line 15 modifies the background color of the form by setting its BackColor property to the dialog's Color property.

Lines 2030 define the btnTextColor_Click event handler. If the user clicks OK in the dialog, lines 2728 set the text color of both buttons to the selected color.

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 Color-Dialog to that color.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

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