So right now I have a number between 0 and 2^24, and I need to map it to three RGB values. I'm having a bit of trouble on how I'd accomplish this. Any assistance is appreciated.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can do
Color c = Color.FromArgb(someInt);
and then use c.R
, c.G
and c.B
for Red, Green and Blue values respectively
回答2:
Depending on which color is where, you can use bit shifting to get the individual colors like this:
int rgb = 0x010203;
var color = Color.FromArgb((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, (rgb >> 0) & 0xff);
The above expression assumes 0x00RRGGBB
but your colors might be 0x00BBGGRR
in which case just change the 16, 8, 0
values around.
This also uses System.Drawing.Color
instead of System.Windows.Media.Color
or your own color class. That depends on the application.
回答3:
You can use the BitConverter
class to get the bytes from the int:
byte[] values = BitConverter.GetBytes(number);
if (!BitConverter.IsLittleEndian) Array.Reverse(values);
The array will have four bytes. The first three bytes contain your number:
byte b = values[0];
byte g = values[1];
byte r = values[2];
回答4:
the above code works grate. just a small correction, need to swap b and r as below.
byte r = values[0];
byte g = values[1];
byte b = values[2];