21
Sep

Convert color string to rgb value

Post a comment » Popularity: 1%

This following codes convert an ordinary color string (eg: #FF0000) into RGB value.

Convert color string to rgb value

convert hex color string to rgb:
public static Color CovnertToColor(string colorString)
{
            byte a = 255;
            byte r = (byte)(Convert.ToUInt32(colorString.Substring(1, 2), 16));
            byte g = (byte)(Convert.ToUInt32(colorString.Substring(3, 2), 16));
            byte b = (byte)(Convert.ToUInt32(colorString.Substring(5, 2), 16));
            return Color.FromArgb(a, r, g, b);
}

// or

public static Color ParseColor(string value)
{
    value = value.Replace("#", "");
    Int32 v = Int32.Parse(value, System.Globalization.NumberStyles.HexNumber);
    return new Color()
    {
        A = 255,
        R = Convert.ToByte((v >> 16) & 255),
        G = Convert.ToByte((v >> 8) & 255),
        B = Convert.ToByte((v >> 0) & 255)
    };
}

// Create random color
Random r = new Random();
byte red = (byte)(255 * r.NextDouble());
byte green = (byte)(255 * r.NextDouble());
byte blue = (byte)(255 * r.NextDouble());
Color color = Color.FromArgb(255, red, green, blue);  
  • DZone
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit

Related Posts

Leave a Reply