C # Круглый цвет в цвета в списке - PullRequest
4 голосов
/ 03 апреля 2011

У меня есть список цветов в формате HEX:

String[] validcolors = new String[]
{
    "0055A5",
    "101010",
    "E4D200",
    "FFFFFF",
    "006563",
    "A97B3E",
    "B80000",
    "6E3391",
    "D191C3",
    "D68200",
    "60823C",
    "AA8D73",
    "73A1B8",
    "6E6D6E",
    "00582C",
    "604421"
};    

И объект цвета:

Color c = ...

Я хочу найти цвет, который ближе всего к c вvalidcolors.Кто-нибудь может мне помочь?Моя первоначальная идея была «ближе к значению RGB», но все, что работает, хорошо.

Ответы [ 3 ]

6 голосов
/ 03 апреля 2011

Я бы подумал о том, чтобы преобразовать гекс в цвет .NET, а затем вычислить somr-вид расстояния ((x2-x1) ² + (y2-y1) ²) и взять ближайший, используя это расстояние:

string closestColor = "";
double diff = 200000; // > 255²x3

foreach(string colorHex in validColors)
{
    Color color = System.Drawing.ColorTranslator.FromHtml("#"+colorHex);
    if(diff > (diff = (c.R - color.R)²+(c.G - color.G)²+(c.B - color.B)²))
        closestColor = colorHex;
}

return closestColor;
2 голосов
/ 03 апреля 2011

Расстояние между двумя цветами зависит от используемой цветовой модели. См. Эту статью в Википедии , поэтому пока мы не знаем, какую модель вы предпочитаете, мы не можем помочь.

0 голосов
/ 24 июня 2015

Вот (многословный) метод с использованием HSB.

float targetHue = c.GetHue();
float targetSat = c.GetSaturation();
float targetBri = c.GetBrightness();

string closestColor = "";
double smallestDiff = double.MaxValue;

foreach (string colorHex in validcolors)
{
    Color currentColor = ColorTranslator.FromHtml("#" + colorHex);
    float currentHue = currentColor.GetHue();
    float currentSat = currentColor.GetSaturation();
    float currentBri = currentColor.GetBrightness();

    double currentDiff = Math.Pow(targetHue - currentHue, 2) + Math.Pow(targetSat - currentSat, 2) + Math.Pow(targetBri - currentBri, 2);

    if (currentDiff < smallestDiff)
    {
        smallestDiff = currentDiff;
        closestColor = colorHex;
    }
}

return closestColor;
...