Skip to content

Instantly share code, notes, and snippets.

@leye0
Created March 3, 2017 04:24
Show Gist options
  • Save leye0/8b8ef19d84facfb76dc3c06859235b00 to your computer and use it in GitHub Desktop.
Save leye0/8b8ef19d84facfb76dc3c06859235b00 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace lol
{
public static class ColorHelpers
{
public static string GetColorName(Color c)
{
return FindClosestColorName(GetNamedColors(), c);
}
private static List<Tuple<string, Color>> GetNamedColors()
{
var colors = typeof(System.Drawing.Color).GetProperties();
return Enum.GetValues(typeof(System.Drawing.KnownColor))
.Cast<System.Drawing.KnownColor>()
.Select(System.Drawing.Color.FromKnownColor)
.Where(c => colors.Any(cc => cc.Name == c.Name))
.Select(c => new Tuple<string, Color>(c.Name, c.ToAnnotationColor()))
.ToList();
}
private static string FindClosestColorName(List<Tuple<string, Color>> colors, Color color)
{
var colorIdentity = color.GetColorIdentity();
var colorsWithHueDistance = colors.Select(otherColor => new { Name = otherColor.Item1, Color = otherColor.Item2, Distance = Math.Abs(otherColor.Item2.GetColorIdentity() - colorIdentity) + otherColor.Item2.GetHueDistance(color) });
var bestColor = colorsWithHueDistance.OrderBy(c => c.Distance);
return bestColor.FirstOrDefault().Name;
}
// https://github.com/mono/mono/blob/master/mcs/class/System.Drawing/System.Drawing/Color.cs
public float GetBrightness()
{
var minval = (byte) Math.Min(R, Math.Min(G, B));
var maxval = (byte) Math.Max(R, Math.Max(G, B));
return (float)(maxval + minval) / 510;
}
public float GetSaturation()
{
var minval = (byte)Math.Min(R, Math.Min(G, B));
var maxval = (byte)Math.Max(R, Math.Max(G, B));
if (maxval == minval)
return 0.0f;
int sum = maxval + minval;
if (sum > 255)
sum = 510 - sum;
return (float)(maxval - minval) / sum;
}
public float GetHue()
{
var r = R;
var g = G;
var b = B;
var minval = (byte)Math.Min(r, Math.Min(g, b));
var maxval = (byte)Math.Max(r, Math.Max(g, b));
if (maxval == minval)
{
return 0.0f;
}
var diff = (float)(maxval - minval);
var rnorm = (maxval - r) / diff;
var gnorm = (maxval - g) / diff;
var bnorm = (maxval - b) / diff;
var hue = 0.0f;
if (r == maxval)
{
hue = 60.0f * (6.0f + bnorm - gnorm);
}
if (g == maxval)
{
hue = 60.0f * (2.0f + rnorm - bnorm);
}
if (b == maxval)
{
hue = 60.0f * (4.0f + gnorm - rnorm);
}
if (hue > 360.0f)
{
hue = hue - 360.0f;
}
return hue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment