Color constructors in XNA Game Studio 4.0

Originally posted to Shawn Hargreaves Blog on MSDN, Wednesday, March 31, 2010

Here’s a subtle improvement I bet you would never notice if I didn’t point it out, but which should save much pulling-out-of-hair for those who previously ran into this issue…

XNA supports two different color formats: byte values ranging 0-255, or floating point values ranging 0-1. The Color struct had constructor overloads accepting either format:

    Color(byte r, byte g, byte b);
    Color(float r, float g, float b);

Well and good, until someone tries something like:

    Color x, y;
    Color z = new Color(x.R + y.R, x.G + y.G, x.B + y.B);

That seems straightforward, but falls foul of an unfortunate interaction between two parts of the C# type system:

Result: values mysteriously end up 255 times larger than you intended. Colors saturate to pure white. Attempted alpha fades saturate to fully opaque. Confusion ensues.

In Game Studio 4.0, we changed the Color constructor overloads to take ints rather than bytes:

    Color(int r, int g, int b);
    Color(float r, float g, float b);

Result:

Blog index   -   Back to my homepage