Converting Hex Colors to RGB Values for Text Formatting

90
0
Tuesday
HaydenWelch
MVP Regular Contributor
3 0 90

Ran into this the other day, had stored the color assignments for a set of features as Hex so I could easily drive Symbol color, but then wanted that color available in the label class was well. There is a `ToHex` function in Arcade, but no reverse `ToDec` function. Luckily it's not that difficult to implement this by hand:

var hexMap = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15}

function HexToDec(code) {
    var val = 0
    code = Reverse(Split(code, ''))
    for (var part in code) { val += (Pow(16, part)) * hexMap[code[part]] }
    return val
}

 This is a simple function that takes an input hex string (e.g. 'f0') and returns the decimal value for it  (e.g. 240). It does this by first splitting the string characters out (['f', '0']), reversing the list and using the current index as the power of 16 to multiply by then looks up the hex character in the `hexMap` dictionary.

val = 0
pow = 0
// Loop 1
hexMap['0'] == 0
val += (16^pow)*0 // (1*0)
pow += 1

// Loop 2
hexMap['f'] = 15
val += (16^pow)*15 // (16*15)
pow += 1

// Done
return val // (240)

Now that we have a way to convert hex substrings to integers, we can use that to consume a hex string and return a list of RGB values:

function HexToRGB(hex) {
    var rDec = HexToDec(Left(hex, 2))
    var gDec = HexToDec(Mid(hex, 2, 2))
    var bDec = HexToDec(Right(hex, 2))
    return [rDec, gDec, bDec]
}
Console(HexToRGB('ff00ff')) // [255,0,255]

 Since each Hex color code is formatted '<rr><gg><bb>', we can use the builtin text functions to extract each character group from the Left, Middle, and Right of the string.

 

Now that we have ordered RGB values, we can easily interpolate them into a text tag:

if ($feature.COLOR != NULL) { rgb = HexToRGB($feature.COLOR) }
var r = rgb[0]
var g = rgb[1]
var b = rgb[2]
var a = 100

var CLROpen = Concatenate(["<CLR red='", r, "' green='", g, "' blue='", b, "' alpha='", a, "'>"], '')

return CLROpen+"My Text"+"</CLR>"

 

In this instance, I hardcoded the alpha value, but if your hexstring contains alpha, you can easily extend the `HexToRGB` function to parse it:

function HexToRGBA(hex) {
    var rDec = HexToDec(Left(hex, 2))
    var gDec = HexToDec(Mid(hex, 2, 2))
    var bDec = HexToDec(Mid(hex, 4, 2))
    var aDec = HexToDec(Right(2))
    return [rDec, gDec, bDec, aDec]
}

Console(HexToRGBA('ff00ff00')) // [255,0,255,0]

 

Hopefully this little snippet can save someone a headache! It's a bit annoying that Symbol colors require hex colors and label text requires RGB values, but luckily this is a pretty small and lightweight conversion.

Contributors
About the Author
Hello! My name is Hayden Welch. I work in the OSP fiber optic design industry and focus heavily on building tools and automations for designing large scale networks using arcpy and ArcGIS Pro