How can you unzip Color.PackedValue

I am trying to save color to a database. I know that I can cut the color into 4 parts, RGBA, but it seems silly to keep the color using 3 columns. Therefore, although I just saved it in a string using a delimiter, or even just used 3 characters for each color. But again, this seems silly. The Color structure has a packingValue property that seems to be doing something with the values ​​to create the uint. but I don’t know how to unpack it. Does anyone have any ideas

Color c = new Color.Black;
uint i = c.PackedValue;
Color newColor=Color.FromUINT(i); // This doesn't work of course
+5
source share
3 answers

PackedValue- read / write property. You do not need to perform any bit offset in order to use it.

var c = new Color() { PackedValue = packedColor };
Console.WriteLine(c.A);
Console.WriteLine(c.R);
Console.WriteLine(c.G);
Console.WriteLine(c.B);
+5
source

From the first Google result :

//First lets pack the color
Color color = new Color(155, 72, 98, 255);
uint packedColor = color.PackedValue;
//Now unpack it to get the original value.
Color unpackedColor = new Color();
unpackedColor.B = (byte)(packedColor);
unpackedColor.G = (byte)(packedColor >> 8);
unpackedColor.R = (byte)(packedColor >> 16);
unpackedColor.A = (byte)(packedColor >> 24);
+2

You need to swap channels B and R when moving bits. IIRC DirectX uses BGRA color, while XNA uses RGBA. Therefore, if we change the sample code above to read

//First lets pack the color
Color color = new Color(155, 72, 98, 255);
uint packedColor = color.PackedValue;
//Now unpack it to get the original value.
Color unpackedColor = new Color();
unpackedColor.R = (byte)(packedColor);
unpackedColor.G = (byte)(packedColor >> 8);
unpackedColor.B = (byte)(packedColor >> 16);
unpackedColor.A = (byte)(packedColor >> 24);

you will get the correct color value back from it

+1
source

All Articles