I’ve had a look at here but I don’t quite understand whats going on there. I’m quite new to c# and I’m trying to make a HEX code gradient generator. I am given two strings of hex codes with a bunch of step down/ups.
for example:
black: 000000 to grey: 666666
with a step of 10.
This would generate 10 different HEX codes that would build me a gradient from these two points. I was wondering how I’d go about this, or if someone could give me an algorithm for how to do this.
Thanks!
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
Colordata 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
Colorfrom uintOne annoying thing about
Color.FromArgb()is that it accepts anintvalue instead ofuint. Thus, feeding it with 0xFF666666 for example will throw and exception.To overcome this, we need to dirty our hands with some bit shifting:
EDIT:
GetColorFromArgbExplainedTo answer the question “how would you convert a hex code into RGB?”, then
GetColorFromArgbalready converts a hex number to R,G,B, but also adds the alpha-channel information.The input for
GetColorFromArgbis a 32-bit unsigned integer. If we look at its hex representation, then its template is: 0xAARRBBGG.GetColorFromArgbextracts the components one after the other by using bit-masks and bit-shifts, and then callingColor.FromArgb(int a, int r, int g, int b).Here’s a more elaborated version of
GetColorFromArgb: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:intinstead of auintinput.