简体   繁体   English

将 Integer 映射到 C# 中的 RGB 颜色

[英]Mapping an Integer to an RGB color in C#

So right now I have a number between 0 and 2^24, and I need to map it to three RGB values.所以现在我有一个介于 0 和 2^24 之间的数字,我需要将其 map 转换为三个 RGB 值。 I'm having a bit of trouble on how I'd accomplish this.我在如何实现这一点上遇到了一些麻烦。 Any assistance is appreciated.任何帮助表示赞赏。

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 and then use c.R , c.G and c.B for Red, Green and Blue values respectively

Depending on which color is where, you can use bit shifting to get the individual colors like this:根据哪个颜色在哪里,您可以使用位移来获得单个 colors,如下所示:

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.上面的表达式假定0x00RRGGBB但您的 colors 可能是0x00BBGGRR在这种情况下只需更改16, 8, 0值。

This also uses System.Drawing.Color instead of System.Windows.Media.Color or your own color class.这也使用System.Drawing.Color代替System.Windows.Media.Color或您自己的颜色 class。 That depends on the application.这取决于应用程序。

You can use the BitConverter class to get the bytes from the int:您可以使用BitConverter class 从 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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM