Mapping an Integer to an RGB color in C#

后端 未结 3 848
挽巷
挽巷 2020-12-29 10:47

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 apprec

相关标签:
3条回答
  • 2020-12-29 10:55

    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];
    
    0 讨论(0)
  • 2020-12-29 11:04

    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.

    0 讨论(0)
  • 2020-12-29 11:16

    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

    0 讨论(0)
提交回复
热议问题