Convert a .NET Color to a hex string. - CSharp System.Drawing

CSharp examples for System.Drawing:Color Convert

Description

Convert a .NET Color to a hex string.

Demo Code


using System.Text;
using System.Linq;
using System.Drawing;
using System.Collections.Generic;
using System;/*  w  w  w .  java  2 s.  c om*/

public class Main{
        /// <summary>
        /// Convert a .NET Color to a hex string.
        /// </summary>
        /// <returns>ex: "FFFFFF", "AB12E9"</returns>
        public static string ToHexString(this Color color)
        {
            byte[] bytes = new byte[3];
            bytes[0] = color.R;
            bytes[1] = color.G;
            bytes[2] = color.B;

            char[] chars = new char[bytes.Length * 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                int b = bytes[i];
                chars[i * 2] = hexDigits[b >> 4];
                chars[i * 2 + 1] = hexDigits[b & 0xF];
            }
            return "#" + new string(chars);
        }
}

Related Tutorials