Converts the hex formatted color to a Color - CSharp System.Drawing

CSharp examples for System.Drawing:Color Convert

Description

Converts the hex formatted color to a Color

Demo Code


using System.Windows.Media;
using System.Windows;
using System.Drawing;
using System.Text;
using System.Collections.Generic;
using System;/*from   w w w.  j av  a2  s.c o  m*/

public class Main{
        /// <summary>
        /// Converts the hex formatted color to a <see cref="Color"/>
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        public static Color FromHex(string hex)
        {
            if (hex.StartsWith("#"))
                hex = hex.Substring(1);

            if (hex.Length != 6) throw new Exception("Color not valid");

            var convertFromString = ColorConverter.ConvertFromString(hex);
            if (convertFromString != null) return (Color) convertFromString;
            return new Color();
        }
}

Related Tutorials