Mapping an Integer to an RGB color in C#

2019-02-03 08:43发布

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.

标签: c# mapping rgb
4条回答
甜甜的少女心
2楼-- · 2019-02-03 09:02

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];
查看更多
Lonely孤独者°
3楼-- · 2019-02-03 09:05

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

查看更多
来,给爷笑一个
4楼-- · 2019-02-03 09:16

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.

查看更多
一夜七次
5楼-- · 2019-02-03 09:26

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];
查看更多
登录 后发表回答