Adding ToArgb() to the Silverlight Color class

23 September 2009

If you’re using existing imaging libraries with your Silverlight applications, they often represent a Color from the System.Drawing world in the full framework as an integer. An ARGB value is a 32-bit integer with the byte-ordering of AARRGGBB. Using some simple bit shifts and an extension method, you can have this functionality in Silverlight as well.

Just add the following class to your project. The extension class is internal, and defined in the same namespace as Color, so it’ll always be accessible:

// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

namespace System.Windows.Media
{
    internal static class ColorExtensions
    {
        public static int ToArgb(this Color color)
        {
            int argb = color.A << 24;
            argb += color.R << 16;
            argb += color.G << 8;
            argb += color.B;

            return argb;
        }
    }
}

Hope this helps!

(And yes, I tried to add this information to the MSDN documentation on ToArgb() using the Community Content feature, but apparently it didn’t like the input. Figuring the search engines will catalog this well enough.)

Jeff Wilcox is a Software Engineer at Microsoft in the Open Source Programs Office (OSPO), helping Microsoft engineers use, contribute to and release open source at scale.

comments powered by Disqus