#211 – Creating a Color Value in Code

Color, defined in System.Windows.Media, is a structure that represents a color by storing Red (R), Green (G) and Blue (B) values as well as an Alpha (A) value indicating opacity.

You can create a color value in code using the Color.FromRgb and Color.FromArgb static methods.

The Color.FromRgb method takes three parameters, allowing you specify the R, G and B components of the color, each of which is in the range 0-255.

            Color lightGreen = Color.FromRgb(120, 255, 0);
            this.Background = new SolidColorBrush(lightGreen);

The Color.FromArgb method also takes a parameter representing the alpha channel (0-255), which dictates the opacity of the color.  A value of 255 represents a fully opaque color and a value of 0 represents a fully transparent color.

            // Set window background to semi-transparent color
            Color lightGreen = Color.FromArgb(50, 120, 255, 0);
            this.Background = new SolidColorBrush(lightGreen);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #211 – Creating a Color Value in Code

  1. adi says:

    Please also specify how to use a color value
    eg . #383fbe97
    Thanking in advance

    • Sean says:

      If your number represents #aarrggbb, then the first two digits represent the Alpha value, so you’d pass them into FromArgb method as 1st parameter. 3rd/4th digits are Red, pass them in as second parameter, etc.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: