Mapping an Integer to an RGB color in C#

跟風遠走 提交于 2019-12-30 01:16:05

问题


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];


来源:https://stackoverflow.com/questions/6131438/mapping-an-integer-to-an-rgb-color-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!