ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ToColor

Convert a (A)RGB string to a Silverlight Color object

Source

using System;
using System.Windows.Media;

static class Extensions {

    /// <summary>
    /// Convert a (A)RGB string to a Color object
    /// </summary>
    /// <param name="argb">An RGB or an ARGB string</param>
    /// <returns>a Color object</returns>
    public static Color ToColor(this string argb) {
        argb = argb.Replace("#", "");
        byte a = System.Convert.ToByte("ff", 16);
        byte pos = 0;
        if (argb.Length == 8) {
            a = System.Convert.ToByte(argb.Substring(pos, 2), 16);
            pos = 2;
        }
        byte r = System.Convert.ToByte(argb.Substring(pos, 2), 16);
        pos += 2;
        byte g = System.Convert.ToByte(argb.Substring(pos, 2), 16);
        pos += 2;
        byte b = System.Convert.ToByte(argb.Substring(pos, 2), 16);
        return Color.FromArgb(a, r, g, b);
    }
}

Example

Color c = "ff00bb".ToColor();
LayoutRoot.Background = new SolidColorBrush(c);

Author: Fons Sonnemans

Submitted on: 23 nov. 2008

Language: C#

Type: System.String

Views: 6279