Simple gradients perform a linear division of a range into equal sections.
For example, if we look just at the red component and we'd like to go from 0 to 250 (decimal) in 5 steps, then each section will be ((250 - 0) / (5 - 1)) = 62.5.
The values will then be: 0, 62.5, 125, 187.5 and 250.
All you have to do now is to repeat this linear division for each component.
About the alpha channel
Note that the Color
data structure contains an alpha-channel value, which is not reflected in the case of your 0x666666. If you consider your value of template 0xRRGGBB and you assume that the alpha channel will be 0xFF (i.e. totally opaque), then all is well.
But if you'd like to include the alpha channel in your gradient (as seen in all examples here), then for the template 0xAARRGGBB, in your case the alpha channel will be 0, which means that the color will be totally transparent (invisible).
Contructing Color
from uint
One annoying thing about Color.FromArgb()
is that it accepts an int
value instead of uint
. Thus, feeding it with 0xFF666666 for example will throw and exception.
To overcome this, we need to dirty our hands with some bit shifting:
private static Color GetColorFromArgb( uint colorValue )
{
Color color = Color.FromArgb(
(int)((colorValue & 0xFF000000) >> 24),
(int)((colorValue & 0x00FF0000) >> 16),
(int)((colorValue & 0x0000FF00) >> 8),
(int)((colorValue & 0x000000FF))
);
return color;
}
EDIT: GetColorFromArgb
Explained
To answer the question "how would you convert a hex code into RGB?", then GetColorFromArgb
already converts a hex number to R,G,B, but also adds the alpha-channel information.
The input for GetColorFromArgb
is a 32-bit unsigned integer. If we look at its hex representation, then its template is: 0xAARRBBGG.
GetColorFromArgb
extracts the components one after the other by using bit-masks and bit-shifts, and then calling Color.FromArgb(int a, int r, int g, int b)
.
Here's a more elaborated version of GetColorFromArgb
:
private static Color GetColorFromArgb(uint colorValue)
{
int a = (int)((colorValue & 0xFF000000) >> 24);
int r = (int)((colorValue & 0x00FF0000) >> 16);
int g = (int)((colorValue & 0x0000FF00) >> 8);
int b = (int)(colorValue & 0x000000FF);
Color color = Color.FromArgb(a, r, g, b);
return color;
}
If the question was how to disregard the alpha-channel, then you can create a GetColorFromRGB()
method that doesn't extract the alpha information and instead passes a fixed value:
private static Color GetColorFromRGB(int colorValue)
{
int a = 0xFF; // Fully opaque
int r = (int)((colorValue & 0x00FF0000) >> 16);
int g = (int)((colorValue & 0x0000FF00) >> 8);
int b = (int)(colorValue & 0x000000FF);
Color color = Color.FromArgb(a, r, g, b);
return color;
}
- Note that since you use 0xRRGGBB values, you can use an
int
instead of a uint
input.