Skip to content

Instantly share code, notes, and snippets.

@Seloris
Last active August 29, 2015 14:27
Show Gist options
  • Save Seloris/bdf417caa3f39e509494 to your computer and use it in GitHub Desktop.
Save Seloris/bdf417caa3f39e509494 to your computer and use it in GitHub Desktop.
/// <summary>
/// Converter used to compare some methods to get a SolidColorBrush from string hex/name colors
/// With the help of Jerome Giacomini (http://jeromegiacomini.net/Blog/2015/08/20/convertir-des-couleurs-hexa-et-des-colorname-en-solidcolorbrush/)
/// And Jonathan Antoine (http://blogs.infinitesquare.com/b/jonathan/archives/astuce-windowsphone-creer-un-objet-%E2%80%98color-a-partir-de-sa-chaine-hexadecimale-string#.VdYkOPntlBd)
/// </summary>
public static class ConverterHelper
{
/// <summary>
/// Gets or sets the limit.
/// </summary>
/// <value>
/// The limit used for iterations (results to Limit^3 colors to test)
/// </value>
public const int Limit = 20;
/// <summary>
/// Runs the comparison.
/// </summary>
/// <param name="argb">if set to <c>true</c> we get only ARGB values, otherwhise we get colors by Name.</param>
public static void RunComparison(bool argb)
{
// Get colors
List<string> colors = null;
if (argb)
{
colors = GetArgbHexaColors().ToList();
}
else
{
colors = GetNameColors().ToList();
}
int iterationCount = 10;
// Init results tabs
var parsingResults = new long[iterationCount];
var xamlReaderResults = new long[iterationCount];
var offsetByteResults = new long[iterationCount];
int i = 0;
while (i < iterationCount)
{
// PARSING
var sw = new Stopwatch();
sw.Start();
foreach (var color in colors)
{
var solidColorBrush = ConverterHelper.ConverterWithParsing(color);
}
sw.Stop();
parsingResults[i] = sw.ElapsedMilliseconds;
// BYTE OFFSET
sw.Restart();
foreach (var color in colors)
{
var solidColorBrush = ConverterHelper.ConverterWithByteOffset(color);
}
sw.Stop();
offsetByteResults[i] = sw.ElapsedMilliseconds;
// XAML READER
sw.Restart();
foreach (var color in colors)
{
var solidColorBrush = ConverterHelper.ConverterWithXamlReader(color);
}
sw.Stop();
xamlReaderResults[i] = sw.ElapsedMilliseconds;
i++;
}
Debug.WriteLine("Results for {0} iterations with {1} colors :", iterationCount, colors.Count);
Debug.WriteLine("Color type used : {0}", argb ? "ARGB" : "By Name");
Debug.WriteLine("{0}ms for Offset Byte", offsetByteResults.Average());
Debug.WriteLine("{0}ms for Xaml Reader", xamlReaderResults.Average());
Debug.WriteLine("{0}ms for Parsing", parsingResults.Average());
}
/// <summary>
/// Gets the name colors.
/// </summary>
/// <returns></returns>
private static IEnumerable<string> GetNameColors()
{
var colorList = new string[]
{
"Red",
"Blue",
"Black",
"AliceBlue",
"AntiqueWhite",
"Aquamarine",
"BlueViolet",
"Coral",
"DarkMagenta",
"Firebrick"
};
var limit = Math.Pow(Limit, 3);
var i = 0;
while (i < limit)
{
yield return colorList[i % colorList.Length];
i++;
}
}
/// <summary>
/// Gets the ARGB hexa colors.
/// </summary>
/// <returns></returns>
public static IEnumerable<string> GetArgbHexaColors()
{
for (byte r = 0; r < Limit; r++)
{
for (byte g = 0; g < Limit; g++)
{
for (byte b = 0; b < Limit; b++)
{
yield return Color.FromArgb(255, r, g, b).ToString();
}
}
}
}
/// <summary>
/// Converter with Byte Offset
/// </summary>
/// <param name="color">The color.</param>
/// <returns></returns>
public static SolidColorBrush ConverterWithByteOffset(string color)
{
if (string.IsNullOrEmpty(color))
return null;
if (color[0] == '#')
{
var v = Convert.ToInt32(color.Substring(1, color.Length - 1), 16);
return new SolidColorBrush(Color.FromArgb((byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)(v >> 0)));
}
else
{
return FromName(color);
}
}
/// <summary>
/// Converter with Xaml Reader
/// </summary>
/// <param name="color">The color.</param>
/// <returns></returns>
public static SolidColorBrush ConverterWithXamlReader(string color)
{
string xamlString = "<Canvas " +
"xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " +
"Background=\"" + color + "\"/>";
var c = XamlReader.Load(xamlString) as Canvas;
if (c != null)
{
return c.Background as SolidColorBrush;
}
return null;
}
///<summary>
/// Obtient un SolidColorBrush à partir d'une couleur string
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public static SolidColorBrush ConverterWithParsing(string color)
{
if (string.IsNullOrEmpty(color))
return null;
return color[0] != '#' ? FromName(color) : FromHex(color);
}
///<summary>
/// Obtient un SolidColorBrush à partir d'une couleur string
/// </summary>
/// <param name="colorName">Nom de la couleur ex: White, Red, Pink</param>
/// <returns>Retourne une brush. Si la couleur n'est pas un nom valide retourne null</returns>
public static SolidColorBrush FromName(string colorName)
{
if (string.IsNullOrEmpty(colorName))
return null;
var colorProperty = typeof(Colors).GetRuntimeProperty(colorName);
if (colorProperty != null)
return new SolidColorBrush((Color)colorProperty.GetValue(null));
return null;
}
///<summary>
/// Convertit un code couleur heaxadecimal en SolidColorBrush
/// </summary>
/// <param name="hexColor">code hexa d'une couleur exemple #FFFFFF</param>
/// <returns>Retourne une brush. Si la couleur n'est pas un code hexadecimal valide retourne null</returns>
public static SolidColorBrush FromHex(string hexColor)
{
if (string.IsNullOrEmpty(hexColor))
return null;
if (hexColor[0] != '#')
return null;
byte a, r, g, b;
if (hexColor.Length == 7)
{
a = 255;
r = ToByte(hexColor.Substring(1, 2));
g = ToByte(hexColor.Substring(3, 2));
b = ToByte(hexColor.Substring(5, 2));
return new SolidColorBrush(Color.FromArgb(a, r, g, b));
}
else if (hexColor.Length == 9)
{
a = ToByte(hexColor.Substring(1, 2));
r = ToByte(hexColor.Substring(3, 2));
g = ToByte(hexColor.Substring(5, 2));
b = ToByte(hexColor.Substring(7, 2));
return new SolidColorBrush(Color.FromArgb(a, r, g, b));
}
else
{
return null;
}
}
///<summary>
/// Convertit une couleur hexadecimal en Alpha, Red, Blue, Green
/// </summary>
/// <param name="colorCodePart">Hexadecimal color code channel (Alpha, Red, Blue, Green)</param>
/// <returns>byte value parsed from Hexadecimal color code channel</returns>
static byte ToByte(string colorCodePart)
{
return byte.Parse(colorCodePart, System.Globalization.NumberStyles.HexNumber);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment