Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 70 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
70
Dung lượng
3,09 MB
Nội dung
[ Team LiB ] 4.6 A Real-World Example: Adding Colors, Pens, and Brushes to the GDI+Painter Application In Chapter 3 we created the GDI+Painter application, which allows us to draw simple objects, such as a line, a rectangle, and an ellipse. In this section we will extend the functionality of GDI+Painter by adding support for brushes and pens. After completing this section, you will be able to select a pen color and its width, color transparency, and brush color. Figure 4.32 shows the modified version of GDI+Painter without any objects Figure 4.32. GDI+Painter with pen and brush support Transparency is a component of the color in GDI+. In the .NET Framework library, the Color structure represents a color. It has four components: alpha (A), red (R), green (G), and blue (B). The alpha component of the Color structure represents the transparency of a color. The alpha component values vary from 0 to 255, where 0 is fully transparent and 255 is fully opaque. To create a transparent brush or pen, we create a color using the alpha value and use the color to create a pen or a brush. We will discuss colors and alpha transparency in more detail in Chapter 5 (ARGB is the focus of Section 5.2). This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. The following code snippet shows how to create a color with transparency. We use the same method to add transparency to our application. Color clr = Color.FromArgb(Convert.ToInt16 (TransCounter.Value.ToString()), PenBtn.BackColor.R, PenBtn.BackColor.G, PenBtn.BackColor.B); In our modified version of GDI+Painter, the width selector numeric up-down control allows you to select the width of the pen. A pen is used when we draw the outlines of graphics shapes. A brush is used when we draw filled graphics shapes. The Pen color and Brush color buttons launch ColorDialog, which lets us select a color and set the color of the button itself, which later is used by the program when creating a Pen or Brush object. Listing 4.27 shows the code for these two button click event handlers. This code also sets the background color of the respective buttons to set the current selected color of our brush and pen. Listing 4.27 Selecting pen and brush colors private void PenSettings_Click(object sender, System.EventArgs e) { ColorDialog colorDlg = new ColorDialog(); colorDlg.ShowDialog(); PenBtn.BackColor = colorDlg.Color; } private void BrushSettings_Click(object sender, System.EventArgs e) { ColorDialog colorDlg = new ColorDialog(); colorDlg.ShowDialog(); BrushBtn.BackColor = colorDlg.Color; } When we draw a graphics shape, we set the color, width, and transparency of the pen and brush according to the selection. The last two changes in our revised version of GDI+Painter are on the mouse-up event handler and the form's paint event handler, respectively. The modified mouse-up event handler is shown in Listing 4.28. In it, we use the color buttons to create our current pen and brush from the selected colors. Listing 4.28 The mouse-up event handler private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { // Set the pen's color curPen.Color = Color.FromArgb(Convert.ToInt16( TransCounter.Value.ToString()), PenBtn.BackColor.R, PenBtn.BackColor.G, PenBtn.BackColor.B); // Set the pen's width curPen.Width = (float)PenWidthCounter.Value; // Set the brush's color curBrush.Color = Color.FromArgb(Convert.ToInt16( TransCounter.Value.ToString()), This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. BrushBtn.BackColor.R, BrushBtn.BackColor.G, BrushBtn.BackColor.B); diffX = x - curX; diffY = y - curY; switch (drawIndex) { case 1: { // Draw a line curGraphics.DrawLine(curPen, curX, curY, x, y); break; } case 2: { // Draw an ellipse curGraphics.DrawEllipse(curPen, curX, curY, diffX, diffY); break; } case 3: { // Draw a rectangle curGraphics.DrawRectangle(curPen, curX, curY, diffX, diffY); break; } case 4: { // Fill rectangle curGraphics.FillRectangle(curBrush, curX, curY, diffX, diffY); break; } case 5: { // Fill ellipse curGraphics.FillEllipse(curBrush, curX, curY, diffX, diffY); break; } } // Refresh RefreshFormBackground(); // Set dragMode to false dragMode = false; } The same procedure is applied to the form's paint event handler, shown in Listing 4.29. This code sets the Color and Width properties of our pen and the Color property of our brush according to the current values. Listing 4.29 The form's paint event handler private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. { // Set current pen's color curPen.Color = Color.FromArgb( Convert.ToInt16( TransCounter.Value.ToString()), PenBtn.BackColor.R, PenBtn.BackColor.G, PenBtn.BackColor.B); // Set pen's width curPen.Width = (float)PenWidthCounter.Value; // Set current brush's color curBrush.Color = Color.FromArgb( Convert.ToInt16( TransCounter.Value.ToString()), BrushBtn.BackColor.R, BrushBtn.BackColor.G, BrushBtn.BackColor.B); Graphics g = e.Graphics; // If dragMode is true, draw selected // graphics shape if (dragMode) { switch (drawIndex) { case 1: { g.DrawLine(curPen, curX, curY, x, y); break; } case 2: { g.DrawEllipse(curPen, curX, curY, diffX, diffY); break; } case 3: { g.DrawRectangle(curPen, curX, curY, diffX, diffY); break; } case 4: { g.FillRectangle(curBrush, curX, curY, diffX, diffY); break; } case 5: { g.FillEllipse(curBrush, curX, curY, diffX, diffY); break; } } } } This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. If you run the revised GDI+Painter application, you can set the colors of the brush and the pen, the pen's width, and the transparency of both the pen and the brush. Figure 4.33 shows lines, rectangles, and ellipses drawn with different sizes and transparency. Figure 4.33. GDI+Painter in action 4.6.1 Improvements in GDI+Painter You can improve the functionality of the GDI+Painter application (or your own applications) even more: As we have discussed in our examples, you can add a brush selection feature. You can allow users to select a brush type, style, and other properties. If users pick a gradient brush, they can select colors. You can also allow users to select cap and line styles. For solid brushes, users should be able to pick a color; for texture brushes, they should be able to pick an image; and for hatch and gradient brushes, they should be able to pick styles, background, foreground, and other color properties. You can even add transformation and other options—all of which we've discussed in this chapter. On the basis of this example, you can write your own graphics tool library with support for many more options than the standard Windows PaintBrush application! [ Team LiB ] This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. [ Team LiB ] SUMMARY In this chapter we learned how to work with pens and brushes by using classes from the GDI+ .NET Framework class library. The chapter began by showing how to represent various kinds of brushes in GDI+. We learned the classes for the different brushes and how to use their properties and methods. After covering brushes, the discussion moved on to pens and how to represent them using GDI+ classes. We learned pen-related classes and their properties and methods, and how to add various styles to pens, such as cap, line, and dash styles. We also discussed system pens and brushes, and how to use GDI+ classes to represent and use system pens and brushes. At the end of the chapter we added options for pens and brushes to the GDI+Painter application. You should now have a pretty good idea of how to use pens and brushes in your own applications. After pens and brushes, the next most frequently used graphics objects are text, fonts, and colors. We will discuss these in Chapter 5. [ Team LiB ] This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. [ Team LiB ] Chapter 5. Colors, Fonts, and Text Three types of objects that are used to build graphics-intensive applications are colors, fonts, and text. In this chapter you will learn about the representation of colors, fonts, and text in the .NET Framework class library. We will cover the following topics: Basics of colors, fonts, and text and how they are represented in Windows Namespaces, classes, and other objects provided by the .NET Framework library to work with colors, fonts, and text System fonts, colors, brushes, and pens Color conversions and translations System and private font collections Formatting text using hinting, tab stops, and other methods Setting the quality and performance of text rendering Writing a simple text editor application Text transformation operations such as scaling, rotation, and translation Advanced typography [ Team LiB ] This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. [ Team LiB ] 5.1 Accessing the Graphics Object There are several ways an application can use the code from this chapter. It can execute code using the OnPaint method or Form_Paint event, or it can use code with a button or menu click event handler. If an application executes code with Form_Paint or OnPaint, you will need to include the following line at the beginning of the method. Graphics g = e.Graphics; If an application executes code from a button or menu click event handler or elsewhere, you will need to create a Graphics object using CreateGraphics or another method (see Chapter 3 for details) and call the Dispose method to dispose of objects when you're finished with them. The following code snippet gives an example: Graphics g = this.CreateGraphics(); // YOUR CODE HERE // Dispose of GDI+ objects g.Dispose(); Note To test code from this chapter, we will create a Windows application with code written on the menu item click event handlers. [ Team LiB ] This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. [ Team LiB ] 5.2 Working with Colors In this section we will examine color representation in GDI+ and how to use color-related functionality in real-world applications. In GDI+, a color is represented by a 32-bit structure made up of four components: alpha (A), red (R), green (G), and blue (B), referred to as ARGB mode. Components' values range from 0 to 255. The alpha component (the first 8 bits) of the color represents transparency, which determines how a color is blended with the background. An alpha value of 0 represents a fully transparent color, and a value of 255 represents a fully opaque color; intermediate values produce results between these extremes. Real-world examples of alpha use include drawing translucent graphics shapes and images. Chapter 9 discusses the alpha component in more detail (see Section 9.6). 5.2.1 Color Spaces It's hard for human beings—as perceptual entities—to describe and represent colors. Color spaces provide a common frame of reference that helps represent colors. A color space contains components called color channels. For example, RGB space is a three-dimensional space with red, green, and blue color channels. To limit our discussion, we will cover the RGB (red-green-blue), HSV (hue-saturation-value), and HLS (hue-lightness-saturation) color spaces. The RGB color space is the most commonly used namespace in computer programming because it closely matches the structure of most display hardware—which commonly includes separate red, green, and blue subpixel structures. It can be thought of as a cube in which length indicates the intensity of red, width indicates the intensity of green, and height indicates the intensity of blue. The corner indicated by (0, 0, 0) is black, and the opposite corner (255, 255, 255) is white. Every other color available is represented somewhere between those corners. The HSV, sometimes called HSB (hue-saturation-brightness), and HLS color spaces can be thought of as single and double cones. The hue component represents the position on the cone as an angular measurement. The 0-, 120-, and 240-degree values of hue represent the colors red, green, and blue, respectively. The saturation component describes the color intensity. A saturation value of 0 means gray (colorless), and the maximum value of saturation indicates pure color and brightness for the values specified by the hue and value components. The value, or brightness, component represents the brightness of the color. A value of 0 indicates the color black (no brightness), and a maximum value indicates that the color is brightest (closest to white). The Color structure provided by the .NET Framework library is based on the RGB color space. In Section 5.2.2 we will discuss how to use it in our applications. 5.2.2 The Color Structure The Color structure represents ARGB colors in GDI+. This class has a static member property for almost every possible color. For example, Color.Black and Color.Red represent the colors black and red, respectively. Besides these static properties, this structure includes read-only properties—A, R, G, and B—that represent the alpha, red, green, and blue components, respectively. This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. The IsEmpty property checks whether a Color structure has been initialized (if not, there is no color). The KnownColor enumeration contains more than 300 colors, and each color is represented by its name. For example, Blue and Black members represent the colors blue and black, respectively. KnownColor also defines color combinations, such as LimeGreen and LightBlue. You can also find system colors such as ActiveBorder, ActiveCaption, Control, ControlText, Highlight, and InactiveBorder, using the IsSystemColor enumeration. The Name property represents the name of the color, which is a read-only property. The Transparent property is a static property that represents a transparent color. The Color structure also provides some methods. The FromArgb method creates a color from the four ARGB components. This method has different overloaded forms with which an application can create a Color object from an alpha value only; from an alpha value with a Color object only; from three values (red, green, and blue); and from all four values (alpha, red, green, and blue). The FromKnownColor and FromName methods create a Color object from a predefined color or from the name of a predefined color, respectively. The FromKnownColor method takes only one argument, of KnownColor enumeration. The FromName method takes one argument of string type as the color name. All members defined in the KnownColor enumeration are valid names for this method. Note All three "from" methods (FromArgb, FromKnownColor, and FromName) are static. The ToArgb and ToKnownColor methods convert an ARGB or KnownColor value, respectively, to a Color structure. Listing 5.1 illustrates different ways to create Color objects and use them in an application to draw various graphics objects, including a filled ellipse with a red brush, a filled rectangle with a blue brush, and a line with a green pen. The application first creates four Color objects via the FromArgb, FromName, FromKnownColor, and Empty methods. The FromArgb method creates a translucent pure red Color object, using parameters 120, 255, 0, and 0. The FromName method creates a Color object from the string "Blue". The FromKnownColor method creates a color object from the known color Green. Listing 5.1 Using the methods and properties of the Color structure private void ColorStructMenu_Click(object sender, System.EventArgs e) { // Create Graphics object Graphics g = this.CreateGraphics(); // Create Color object from ARGB Color redColor = Color.FromArgb(120, 255, 0, 0); // Create Color object form color name Color blueColor = Color.FromName("Blue"); // Create Color object from known color Color greenColor = Color.FromKnownColor(KnownColor.Green); // Create empty color Color tstColor = Color.Empty; // See if a color is empty if(tstColor.IsEmpty) { tstColor = Color.DarkGoldenrod; This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. [...]... window title bar background color ActiveCaptionText Active window title bar text color AppWorkspace Multiple-document interface (MDI) workspace background color Control Control background color ControlDark 3D control shadow color ControlDarkDark 3D control dark shadow color ControlLight 3D control highlight color ControlLightLight 3D control light highlight color ControlText Text color of controls Desktop... Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); string str = "#FF00FF"; ColorConverter clrConverter = new ColorConverter(); Color clr1 = (Color)clrConverter.ConvertFromString(str); // Use colors SolidBrush clr2 = new SolidBrush(clr1); SolidBrush clr3 = new SolidBrush(clr1); // Draw GDI+ objects g.FillEllipse(clr2, 10, 10, 50, 50); g.FillRectangle(clr3, 60, 10, 50, 50); // Dispose of objects... of values Listing 5 .4 uses the ColorConverter class methods to convert colors We store a color in a string and call the ConvertFromString method, which returns the Color object Later we will use theColor objects to create two brushes that we will use to fill a rectangle and an ellipse Listing 5 .4 Using the ColorConverter class to convert colors private void ColorConvert_Click(object sender, System.EventArgs... desktop color GrayText Disabled text color Highlight Highlighted text background color HighlightText Highlighted text color HotTrack Hot track color InactiveBorder Inactive window border color InactiveCaption Inactive window caption bar color InactiveCaptionText Inactive window caption bar text color Info ToolTip background color InfoText ToolTip text color Menu Menu background color MenuText Menu text color... to set colors of a few Windows controls In this code we set the background colors of a text box, a radio button, and a button to inactive border, active caption, and control dark system colors, respectively textBox1.BackColor = SystemColors.InactiveBorder; radioButton1.BackColor = SystemColors.ActiveCaption; button1.BackColor = SystemColors.ControlDarkDark; If you're wondering whether you can create... accessing values and properties of types The TypeConverter class serves as a base class for many conversion classes, and ColorConverter and FontConverter are two of them We will discussFontConverter in more detail later in this chapter Some of the common methods of the TypeConverter class (which are available in theColorConverter class) are described in This document was created by an unregistered ChmMagic,... // Get cell descent int cellDescent = fnt.FontFamily.GetCellDescent(fnt.Style); // Get font height int emHeight = fnt.FontFamily.GetEmHeight(fnt.Style); // Get free space float free = cellSpace - (cellAscent + cellDescent); // Display values string str = "Cell Height:" + lnSpace.ToString() + ", Line Spacing: "+cellSpace.ToString() + ", Ascent:"+ cellAscent.ToString() + ", Descent:"+ cellDescent.ToString()... void ColorTranslator_Click(object sender, System.EventArgs e) { Graphics g = this.CreateGraphics(); // Translate colors Color win32Color = ColorTranslator.FromWin32(0xFF0033); Color htmlColor = ColorTranslator.FromHtml("#00AAFF"); // Use colors SolidBrush clr1 = new SolidBrush(win32Color); SolidBrush clr2 = new SolidBrush(htmlColor); // Draw GDI+ objects g.FillEllipse(clr1, 10, 10, 50, 50); g.FillRectangle(clr2,... unhandled exception when executed If you create a pen using SystemColors, however, you can modify its width like this: Pen pn = new Pen(SystemColors.HighlightText); Pn.Width = 4; 5.2 .4 The ColorConverter and ColorTranslator Classes The ColorConverter class is used to convert colors from one data type to another This class is inherited from the TypeConverter class, which defines the functionality for conversion... object Graphics g = this.CreateGraphics(); // Create a Font object Font fnt = new Font("Verdana", 10); // Get height This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks float lnSpace = fnt.GetHeight(g); // Get line spacing int cellSpace = fnt.FontFamily.GetLineSpacing(fnt.Style); // Get cell ascent int cellAscent = fnt.FontFamily.GetCellAscent(fnt.Style); . Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); string str = "#FF00FF"; ColorConverter clrConverter = new ColorConverter(); Color clr1 = (Color)clrConverter.ConvertFromString(str); . background color Control Control background color ControlDark 3D control shadow color ControlDarkDark 3D control dark shadow color ControlLight 3D control highlight color ControlLightLight 3D control. track color InactiveBorder Inactive window border color InactiveCaption Inactive window caption bar color InactiveCaptionText Inactive window caption bar text color Info ToolTip background color InfoText ToolTip