我让这段代码在 C# 中工作。我想帮助将其翻译成惯用的 PowerShell 脚本,该脚本将 rgb 或 hex 颜色定义作为输入,并将前 3 或 5 个匹配项输出到控制台,包括颜色名称和 rgb 值。我对 PowerShell 很陌生,很抱歉,如果这要求太多。
private static void FindMyColor()
{
System.Drawing.Color targetColor = System.Drawing.Color.FromArgb(red: 0, green: 128, blue: 0);
var myStuff = EnumerateColors(targetColor: targetColor).OrderBy(tpl => tpl.Item1).ToList();
int a = 0; // Pause the debugger here.
}
private static double GetColorDistance(System.Drawing.Color lhs, System.Drawing.Color rhs)
{
double sum = Cube(lhs.R - rhs.R) + Cube(lhs.G - rhs.G) + Cube(lhs.B - rhs.B);
return Math.Pow(sum, 1.0/3.0);
}
private static double Cube(int value)
{
return (double) (value * value * value);
}
private static System.Collections.Generic.IEnumerable<Tuple<double, string, System.Drawing.Color>> EnumerateColors(System.Drawing.Color targetColor)
{
var candidateColors = EnumerateSystemColors();
foreach (string colorName in candidateColors.Keys)
{
var color = candidateColors[key: colorName];
double colorDistance = GetColorDistance(lhs: color, rhs: targetColor);
yield return new Tuple<double, string, System.Drawing.Color>(colorDistance, colorName, color);
}
}
private static System.Collections.Generic.Dictionary<string, System.Drawing.Color> EnumerateSystemColors()
{
var properties = typeof(System.Drawing.Color)
.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy);
return properties.ToDictionary(p => p.Name, p => (System.Drawing.Color)p.GetValue(null, null));
}