In an app it can be interesting to have several shades of the same color.
To do this, I've created a small helper for lightening or darkening a color.
The principle of this helper is simple for each color (R/G/B), I reduce or amplify the color by a percentage.
///
/// Helper permettant de manipuler des couleurs
///
public static class ColorHelper
{
///
/// Assombrit une couleur
///
/// couleur à assombrir
/// pourcentage
///
/// si le pourcentage n'est pas entre 0 et 100
public static Color Darkerise(this Color color, byte percentage = 80)
{
CheckIsValidPercentage(percentage);
var r = color.R;
var g = color.G;
var b = color.B;
r = Darkerise(r, percentage);
g = Darkerise(g, percentage);
b = Darkerise(b, percentage);
return Color.FromArgb(255, r, g, b);
}
static byte Darkerise(byte color, byte percentage)
{
double result = (double)color * (double)percentage / 100d;
if (result < 0)
result = 0;
if (result > 255)
result = 255;
return (byte)result;
}
///
/// Eclaircit une couleur
///
/// couleur à éclaircir
/// pourcentage
///
/// si le pourcentage n'est pas entre 0 et 100
public static Color Lighterise(this Color color, byte percentage = 80)
{
CheckIsValidPercentage(percentage);
var r = color.R;
var g = color.G;
var b = color.B;
r = Lighterise(r, percentage);
g = Lighterise(g, percentage);
b = Lighterise(b, percentage);
return Color.FromArgb(255, r, g, b);
}
static byte Lighterise(byte color, byte percentage)
{
double result = ((double)color * (double)percentage / 100d) + (255d - (double)percentage / 100d * 255d);
if (result < 0)
result = 0;
if (result > 255)
result = 255;
return (byte)result;
}
static void CheckIsValidPercentage(byte percentage)
{
if (percentage < 0 || percentage > 100)
throw new ArgumentException("percentage");
}
}
Example of use:
var color = Color.FromArgb(255, 80, 158, 47);
rect1.Fill = new SolidColorBrush(color.Darkerise());
rect2.Fill = new SolidColorBrush(color.Lighterise());
I'm going to try it.](https://infiniteblogs.blob.core.windows.net/medias/6029/sample_210B5840.png)
Happy coding Original illustration unavailable: You smile