Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you unpack a Color.PackedValue

Tags:

c#

xna

I am trying save a Color to a database. I know I could cut the color into 4 parts, RGBA but it seems silly to save a color using 3 columns. So then I though of simply saving it to a string using a limiter, or even just using 3 characters per color. But again it seems silly. The Color structure has an packedValue Property, which seems to do something with the values to create a uint. but I don't know how to unpack it. Anyone have any ideas

Color c = new Color.Black;
uint i = c.PackedValue;
Color newColor=Color.FromUINT(i); // This doesn't work of course
like image 928
General Grey Avatar asked Mar 13 '13 18:03

General Grey


3 Answers

PackedValue is a read/write property. You don't need to do any bit shifting to make use of it.

var c = new Color() { PackedValue = packedColor };
Console.WriteLine(c.A);
Console.WriteLine(c.R);
Console.WriteLine(c.G);
Console.WriteLine(c.B);
like image 56
Cole Campbell Avatar answered Nov 12 '22 12:11

Cole Campbell


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);
like image 39
Jeff-Meadows Avatar answered Nov 12 '22 14:11

Jeff-Meadows


You need to swap the B and R channels when doing the bit shifting. IIRC DirectX uses BGRA color while XNA uses RGBA. So if we modify 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 out of it

like image 1
Steve Medley Avatar answered Nov 12 '22 13:11

Steve Medley