How to Use HTML Colors in C#
By FoxLearn 12/26/2024 9:13:41 AM 29
This class provides various methods to create and manipulate color values, making it easier to work with colors in your applications.
1. Using an HTML color code (Hexadecimal string)
You can convert an HTML string representing a color (e.g., #D3D3D3
) into a Color
object using the ColorTranslator.FromHtml
method:
var lightGray = System.Drawing.ColorTranslator.FromHtml("#D3D3D3");
2. Using RGB values in hexadecimal format
Another approach is to use the FromArgb
method with three hexadecimal values representing the red, green, and blue components:
var lightGray = System.Drawing.Color.FromArgb(0xD3, 0xD3, 0xD3);
3. Using predefined color names
The Color
class provides a set of named colors. For example, you can directly use the predefined LightGray
color:
var lightGray = Color.LightGray;
4. Specifying transparency (Alpha channel)
You can specify an alpha value (opacity level) in addition to the RGB values. The first parameter in FromArgb
represents the alpha value, where 255
is fully opaque, and 0
is fully transparent:
var lightGray = Color.FromArgb(255, 0xD3, 0xD3, 0xD3); // Fully opaque
5. Using integer RGB values
If you prefer to use integer values for RGB, you can provide them directly in the FromArgb
method:
var lightGray = Color.FromArgb(255, 211, 211, 211); // Fully opaque
6. Working with WPF (Windows Presentation Foundation)
If you're working with WPF and want to specify a color with transparency using the HTML-style format (#AARRGGBB
), you can use the ColorConverter
class:
using System.Windows.Media; var lightGray = (Color)ColorConverter.ConvertFromString("#FFD3D3D3");
All these methods result in the same Color
object, so you can choose whichever approach suits your needs. Whether you’re working with HTML color strings, RGB values, or predefined color names, the .NET Color
class makes it easy to handle color operations in your C# projects.