Computer Magic Logo
Color

Sunday, April 10, 2016

Published by Aristotelis Pitaridis

The controls have two properties which allow us to change the color of the text and the background color.

<Label x:Name="MyLabel" Text="Label" TextColor="Yellow" BackgroundColor="Green" />

We can change the colors programmatically using the following code.

MyLabel.TextColor = Color.Yellow;
MyLabel.BackgroundColor = Color.Green;

We can create our own color values using the following three constructors of the Color class.

new Color(double grayShade)
new Color(double r, double g, double b)
new Color(double r, double g, double b, double a)

The Color class has also the following static member functions.

Color.FromRgb(double r, double g, double b)
Color.FromRgb(int r, int g, int b)
Color.FromRgba(double r, double g, double b, double a)
Color.FromRgba(int r, int g, int b, int a)
Color.FromHsla(double h, double s, double l, double a)

The double values can have a range from 0 to 1 and the integer values can have a range from 0 to 255.

We have to be careful when we use the member functions because we may confuse the compiler and get the wrong value. For example when we use the following command the compiler assumes that the values are integer.

Color.FromRgb(1, 0, 0)

In order to make sure that the compiler will use this value as double we have to define using the following syntax.

Color.FromRgb(1.0, 0, 0)

We can also modify the value of a Color object using the following member functions.

AddLuminosity(double delta)
MultiplyAlpha(double alpha)
WithHue(double newHue)
WithLuminosity(double newLuminosity)
WithSaturation(double newSaturation)

The Color object has also the following useful read only properties and constant.

Color.Default
Color.Accent
Color.Transparent

The Color.Default property can be used in order to set a color value back to the platform default which is different color on each platform.

The Color.Accent property is different depending on the operating system our application is running. On Windows Phone, this is the color chosen by the user. Good Windows Phone applications use this as part of their styling to provide a native look and feel. On iOS and Android this instance is set to a contrasting color that is visible on the default background but is not the same as the default text color.

The Color.Transparent constant can be used in order to clear the color of an element.