TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Color Examples

This C# article explores the Color type. It provides many Color examples.

Color is a struct. This type provides a standard way to specify and mutate colors in the C# language.

By adding a reference to the System.Drawing assembly, you can access this type and avoid writing your own color routines.

Struct

Example. First, let's examine a program that uses a named color property. It then accesses several instance properties on the variable and also calls methods. You can acquire many known colors by using the named properties on the Color type.

Note: For a more complete list, please scroll down and view the names themselves.

Colors can be represented as ARGB values, which store the alpha transparency, as well as the red, green and blue values. These values are stored as bytes which gives them a range of 0 to 255 inclusive.

Byte

C# program that demonstrates Color type

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
	// Get the AliceBlue color.
	Color color = Color.AliceBlue;
	// Write some details about the color.
	Console.WriteLine(color);
	Console.WriteLine(color.ToArgb());
	Console.WriteLine(color.A);
	Console.WriteLine(color.R);
	Console.WriteLine(color.G);
	Console.WriteLine(color.B);
	Console.WriteLine(color.GetBrightness());
	Console.WriteLine(color.GetHue());
	Console.WriteLine(color.GetSaturation());
    }
}

Output

Color [AliceBlue]
-984833
255
240
248
255
0.9705882
208
1

Won't compile? If you try to execute this program and it won't compile, please try adding the System.Drawing assembly through the interface in Visual Studio. Some project types, such as Windows Forms, include this assembly automatically.

Known colors. Occasionally, you may have a known color and want to acquire a Color struct from it for usage elsewhere. For example, you can query the system for the color of the menu text, using the KnownColor.MenuText enum.

And: Then convert it into a regular color. This lets you examine the components of the color programmatically.

C# program that uses known colors

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
	// You can see what the menu text color is.
	Color color = Color.FromKnownColor(KnownColor.MenuText);
	// All values are zero so it is black.
	Console.WriteLine(color.R);
	Console.WriteLine(color.G);
	Console.WriteLine(color.B);
    }
}

Output

0
0
0

Convert. It is possible to represent colors as an integer that represents the byte values of the ARGB values. Each of those values is one byte. The four bytes together constitute a single 32-bit integer.

You can persist the ARGB integer to text files or databases to save storage space. It also will occupy less memory in your program as it executes. Please notice how the ToArgb() and FromArgb() methods are used to go back and forth.

C# program that uses ARGB values

using System.Drawing;

class Program
{
    static void Main()
    {
	// Get ARGB of black.
	int argb = Color.Black.ToArgb();
	// Get the color black by using the argb integer.
	Color color = Color.FromArgb(argb);
    }
}

FromName. In some cases, you may have to convert from a string to a color type. For example, if you accept user input and the user types the word "white", you can convert this into a real color and use it with the Color.FromName method.

Note: This won't work for color names that are not recognized in the list of properties.

C# program that uses FromName and string

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
	// Create the color from a string.
	Color white = Color.FromName("white");
	// Color will have appropriate R G B values.
	Console.WriteLine(white.R);
	Console.WriteLine(white.G);
	Console.WriteLine(white.B);
    }
}

Output

255
255
255

Empty colors. The Color type is a struct type, and so cannot be set to null. Instead of using null, please use the Color.Empty value. Then, whenever you want to see if the color is still empty, acquire the IsEmpty instance property on the variable.

Here: This example shows one case where the color is empty, and one case where the color is not empty.

C# program that uses empty colors

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
	// Color is a struct so it cannot be null.
	// ... Use Color.Empty instead.
	Color color = Color.Empty;
	Console.WriteLine(color.IsEmpty);
	color = Color.Black;
	Console.WriteLine(color.IsEmpty);
    }
}

Output

True
False

Windows Forms. A common place to use the Color type is in the Windows Forms framework. The WPF framework also uses Color instances. Forms require the Color type for when you want to set their backgrounds and foregrounds.

ForeColor, BackColor

In this example, we use the Color.FromName method to convert the string value into an actual color. We then set the form's background to that color. This results in a thoroughly green window.

C# program that uses BackColor property

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication16
{
    public partial class Form1 : Form
    {
	public Form1()
	{
	    InitializeComponent();
	}

	private void Form1_Load(object sender, EventArgs e)
	{
	    // You can assign colors to the BackColor property in Windows Forms.
	    this.BackColor = Color.FromName("green");
	}
    }
}

Named colors. There are many different known and named colors in the .NET Framework. These are accessible through static properties on the Color type. Please see the first example to see how to get the color values.

Also: This site shows the visual appearance of these colors in another article.

Color Table

Named color list

Transparent
AliceBlue
AntiqueWhite
Aqua
Aquamarine
Azure
Beige
Bisque
Black
BlanchedAlmond
Blue
BlueViolet
Brown
BurlyWood
CadetBlue
Chartreuse
Chocolate
Coral
CornflowerBlue
Cornsilk
Crimson
Cyan
DarkBlue
DarkCyan
DarkGoldenrod
DarkGray
DarkGreen
DarkKhaki
DarkMagenta
DarkOliveGreen
DarkOrange
DarkOrchid
DarkRed
DarkSalmon
DarkSeaGreen
DarkSlateBlue
DarkSlateGray
DarkTurquoise
DarkViolet
DeepPink
DeepSkyBlue
DimGray
DodgerBlue
Firebrick
FloralWhite
ForestGreen
Fuchsia
Gainsboro
GhostWhite
Gold
Goldenrod
Gray
Green
GreenYellow
Honeydew
HotPink
IndianRed
Indigo
Ivory
Khaki
Lavender
LavenderBlush
LawnGreen
LemonChiffon
LightBlue
LightCoral
LightCyan
LightGoldenrodYellow
LightGreen
LightGray
LightPink
LightSalmon
LightSeaGreen
LightSkyBlue
LightSlateGray
LightSteelBlue
LightYellow
Lime
LimeGreen
Linen
Magenta
Maroon
MediumAquamarine
MediumBlue
MediumOrchid
MediumPurple
MediumSeaGreen
MediumSlateBlue
MediumSpringGreen
MediumTurquoise
MediumVioletRed
MidnightBlue
MintCream
MistyRose
Moccasin
NavajoWhite
Navy
OldLace
Olive
OliveDrab
Orange
OrangeRed
Orchid
PaleGoldenrod
PaleGreen
PaleTurquoise
PaleVioletRed
PapayaWhip
PeachPuff
Peru
Pink
Plum
PowderBlue
Purple
Red
RosyBrown
RoyalBlue
SaddleBrown
Salmon
SandyBrown
SeaGreen
SeaShell
Sienna
Silver
SkyBlue
SlateBlue
SlateGray
Snow
SpringGreen
SteelBlue
Tan
Teal
Thistle
Tomato
Turquoise
Violet
Wheat
White
WhiteSmoke
Yellow
YellowGreen

Summary. By providing a unified interface for acquiring and mutating color values, the Color type fills a useful niche in the .NET Framework. It is found in the System.Drawing namespace and assembly.

So: You can access known colors, convert colors to integers, parse colors, and generally make the world a brighter place with this type.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf