Identify the closest known color

I allow users of my application to select custom colors and want a friendly name for each color to be displayed instead of displaying a text representation of the hex code.

How to find the closest one System.Drawing.Colorfor a given hex code?

+4
source share
1 answer

Hope this helps someone ...

Public Function GetClosestColor(hex_code As String) As Color
    Dim c As Color = ColorTranslator.FromHtml(hex_code)
    Dim closest_distance As Double = Double.MaxValue
    Dim closest As Color = Color.White

    For Each kc In [Enum].GetValues(GetType(KnownColor)).Cast(Of KnownColor).Select(Function(x) Color.FromKnownColor(x))
        'Calculate Euclidean Distance
        Dim r_dist_sqrd As Double = Math.Pow(CDbl(c.R) - CDbl(kc.R), 2)
        Dim g_dist_sqrd As Double = Math.Pow(CDbl(c.G) - CDbl(kc.G), 2)
        Dim b_dist_sqrd As Double = Math.Pow(CDbl(c.B) - CDbl(kc.B), 2)
        Dim d As Double = Math.Sqrt(r_dist_sqrd + g_dist_sqrd + b_dist_sqrd)

        If d < closest_distance Then
            closest_distance = d
            closest = kc
        End If
    Next

    Return closest
End Function
+3
source

All Articles