|
|
|
|
|
|
Author Rank:
|
|
Total page views :
980
|
|
Total downloads :
25
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
Three types of object that are used to build graphics intensive applications are colors, fonts and text. In this article 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
Accessing the Graphics Object
There are several ways an application can use the code from this article. 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.
Dim g As Graphics = 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 and call Dispose method to dispose of objects when you're finished with them. The following code snippet gives an example:
Dim g As Graphics = Me.CreatGraphics()
'Your code here 'Dispose of GDI+ objects g.Dispose()
Note: To test code from this article, we will create a windows application with code written on the menu item click event handlers.
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.
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 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 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 indicate intensity of blue .The corner indicated by (0,0,0) is black, and the opposite corner (255,255,255) is white. Every other color is represent 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-degrees 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 indicate 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 application.
The Color structure
The color structure represents ARGB colors in GDI+. This class has 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.
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 represents 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 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 FormName 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" method (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 green pen. The application first creates four Color objects via the FromArgb, FromName, FromknownColor, and Empty methods. The FromArgb methods creates a translucent pure red Color object, using parameters 120, 255, 0, and 0. The FromName method creates 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
Imports System Imports System.Collections.Generic Imports System.ComponentModel Imports System.Data Imports System.Drawing Imports System.Linq Imports System.Text Imports System.Windows.Forms Public Class Form1
Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint Dim g As Graphics = e.Graphics
'Create color object from ARGB Dim redColor As Color = Color.FromArgb(120, 255, 0, 0)
'Create Color Object from color name Dim blueColor As Color = Color.FromName("Blue")
'Create Color object from known color Dim greenColor As Color = Color.FromKnownColor(KnownColor.Green)
'Create Empty Color Dim tstColor As Color = Color.Empty
'See if a color is empty
If tstColor.IsEmpty Then tstColor = Color.DarkGoldenrod End If 'Create brushes and pens from colors Dim redBrush As New SolidBrush(redColor) Dim blueBrush As New SolidBrush(blueColor) Dim greenBrush As New SolidBrush(greenColor) Dim greenPen As New Pen(greenBrush, 4)
'Draw GDI+ objects g.FillEllipse(redBrush, 10, 10, 50, 50) g.FillRectangle(blueBrush, 60, 10, 50, 50) g.DrawLine(greenPen, 20, 60, 200, 60)
'Check property values 'MessageBox.Show ("Color Name:"+blueColor.Name+ ' ", A:"+ blueColor.A.ToString () + ' ", R:"+ blueColor.R.ToString () + ' ", B:" + blueColor.B.ToString () + ' ", G:"+ blueColor.G.ToString ()); 'Dispose of GDI+ objects redBrush.Dispose() blueBrush.Dispose() greenBrush.Dispose() greenPen.Dispose() g.Dispose() End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Create Graphics object Dim g As Graphics = Me.CreateGraphics()
'Create color object from ARGB Dim redColor As Color = Color.FromArgb(120, 255, 0, 0)
'Create Color Object from color name Dim blueColor As Color = Color.FromName("Blue")
'Create Color object from known color Dim greenColor As Color = Color.FromKnownColor(KnownColor.Green)
'Create Empty Color Dim tstColor As Color = Color.Empty
'See if a color is empty
If tstColor.IsEmpty Then tstColor = Color.DarkGoldenrod End If
'Create brushes and pens from colors Dim redBrush As New SolidBrush(redColor) Dim blueBrush As New SolidBrush(blueColor) Dim greenBrush As New SolidBrush(greenColor) Dim greenPen As New Pen(greenBrush, 4)
'Draw GDI+ objects g.FillEllipse(redBrush, 10, 10, 50, 50) g.FillRectangle(blueBrush, 60, 10, 50, 50) g.DrawLine(greenPen, 20, 60, 200, 60) 'Check property values 'MessageBox.Show ("Color Name:"+blueColor.Name+ ' ", A:"+ blueColor.A.ToString () + ' ", R:"+ blueColor.R.ToString () + ' ", B:" + blueColor.B.ToString () + ' ", G:"+ blueColor.G.ToString ()); 'Dispose of GDI+ objects redBrush.Dispose() blueBrush.Dispose() greenBrush.Dispose() greenPen.Dispose() g.Dispose() End Sub End Class
Figure 5.1 shows the output from Listing 5.1.
The GetBrightness, GetHue, and GetSaturation method return a color's brightness, hue, and saturation component values, respectively. Listing 5.2 reads hue, saturation, and brightness components of a color and displays their values on the form by using the DrawString method.
FIGURE 5.1 Creating colors using different methods
LISTING 5.2: Getting brightness, hue, and saturation of a color
Private Sub HSBMenu_Click(ByVal sender As Object, ByVal e As System.EventArgs) 'Create a Graphics object Dim g As Graphics = Me.CreateGraphics()
'Create a color Dim clr As Color = Color.FromArgb(255, 200, 0, 100)
'Get hue, saturation, and brightness components Dim h As Single = clr.GetHue() Dim s As Single = clr.GetSaturation() Dim v As Single = clr.GetBrightness() Dim str As String = (("Hue:" & h.ToString() & vbLf & "Saturation: ") + s.ToString() & vbLf & "Brightness: ") + v.ToString()
'Display data g.DrawString(str, New Font("Verdana", 12), Brushes.Blue, 50, 50)
'Dispose of object g.Dispose() End Sub
Figure 5.2 shows the output from Listing 5.2.The values of hue, saturation, and brightness in this particular color are 330, 1, and 0.3921569, respectively.
FIGURE 5.2: Getting brightness, hue and saturation components of a color
Conclusion
Hope the article would have helped you in understanding Colors, Fonts, and Text in GDI+. Read other articles on GDI+ on the website.
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
|
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|