2012-07-31 12 views

Antwort

2

https://stackoverflow.com/a/7792104/224370 erläutert, wie eine benannte Farbe einem exakten RGB-Wert zugeordnet wird. Um es näher zu bringen, benötigen Sie eine Art Abstandsfunktion, bei der Sie berechnen, wie weit die Farben voneinander entfernt sind. Wenn Sie dies im RGB-Raum tun (Summe der Quadrate der Differenzen in den R-, G- und B-Werten), erhalten Sie keine perfekte Antwort (aber vielleicht gut genug). Ein Beispiel dafür finden Sie in https://stackoverflow.com/a/7792111/224370. Um eine genauere Antwort zu erhalten, müssen Sie möglicherweise zu HSL konvertieren und dann vergleichen.

5

Hier ist ein Code basierend auf Ians Vorschlag. Ich habe es auf eine Anzahl von Farbwerten getestet, scheint gut zu funktionieren.

GetApproximateColorName(ColorTranslator.FromHtml(source)) 

private static readonly IEnumerable<PropertyInfo> _colorProperties = 
      typeof(Color) 
      .GetProperties(BindingFlags.Public | BindingFlags.Static) 
      .Where(p => p.PropertyType == typeof (Color)); 

static string GetApproximateColorName(Color color) 
{ 
    int minDistance = int.MaxValue; 
    string minColor = Color.Black.Name; 

    foreach (var colorProperty in _colorProperties) 
    { 
     var colorPropertyValue = (Color)colorProperty.GetValue(null, null); 
     if (colorPropertyValue.R == color.R 
       && colorPropertyValue.G == color.G 
       && colorPropertyValue.B == color.B) 
     { 
      return colorPropertyValue.Name; 
     } 

     int distance = Math.Abs(colorPropertyValue.R - color.R) + 
         Math.Abs(colorPropertyValue.G - color.G) + 
         Math.Abs(colorPropertyValue.B - color.B); 

     if (distance < minDistance) 
     { 
      minDistance = distance; 
      minColor = colorPropertyValue.Name; 
     } 
    } 

    return minColor; 
} 
+0

Danke so muh Kartan ... :) – fresky

Verwandte Themen