DAX Measure for contrasting colors

ContrastedMyKpiColor =

// Parameters:

// Contrast against - The color against which you want to contrast (ex: a background color). Expected to be a 3 or 6 digit hex code. Ex: #FF0, #FFAABB

// Light option - The color to use if the background is dark

// Dark options - The color to use the background is light



var ContrastAgainst = [MyKpiColor]

var LightOption = "#FFFFFF"

var DarkOption = "#000000"



// Compute relative luminance. If > 0.5 the color is considered "light", otherwise it's "dark"

// https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef

// Convert to supported values. Could add RGB(...) here...

var is6DigitHex = LEN(ContrastAgainst)=7 && LEFT(ContrastAgainst, 1)="#"

var is3DigitHex = LEN(ContrastAgainst)=4 && LEFT(ContrastAgainst, 1)="#"

var As6DigitHex = if(is6DigitHex, ContrastAgainst, if(is3DigitHex, "#"&RIGHT(LEFT(ContrastAgainst, 2))&RIGHT(LEFT(ContrastAgainst, 2))&RIGHT(LEFT(ContrastAgainst, 3))&RIGHT(LEFT(ContrastAgainst, 3))&RIGHT(LEFT(ContrastAgainst, 4))&RIGHT(LEFT(ContrastAgainst, 4))))



var Rbyte1 = RIGHT(LEFT(As6DigitHex,2))

var Rbyte2 = RIGHT(LEFT(As6DigitHex,3))

var Rbyte1AsDec = switch(Rbyte1, "A", 10, "B", 11, "C", 12, "D", 13, "E", 14, "F", 15, value(Rbyte1)) * 16

var Rbyte2AsDec = switch(Rbyte2, "A", 10, "B", 11, "C", 12, "D", 13, "E", 14, "F", 15, value(Rbyte2))

var RsRGB = (Rbyte1AsDec + Rbyte2AsDec)/255



var Gbyte1 = RIGHT(LEFT(As6DigitHex,4))

var Gbyte2 = RIGHT(LEFT(As6DigitHex,5))

var Gbyte1AsDec = switch(Gbyte1, "A", 10, "B", 11, "C", 12, "D", 13, "E", 14, "F", 15, value(Gbyte1)) * 16

var Gbyte2AsDec = switch(Gbyte2, "A", 10, "B", 11, "C", 12, "D", 13, "E", 14, "F", 15, value(Gbyte2))

var GsRGB = (Gbyte1AsDec + Gbyte2AsDec)/255



var Bbyte1 = RIGHT(LEFT(As6DigitHex,6))

var Bbyte2 = RIGHT(LEFT(As6DigitHex,7))

var Bbyte1AsDec = switch(Bbyte1, "A", 10, "B", 11, "C", 12, "D", 13, "E", 14, "F", 15, value(Bbyte1)) * 16

var Bbyte2AsDec = switch(Bbyte2, "A", 10, "B", 11, "C", 12, "D", 13, "E", 14, "F", 15, value(Bbyte2))

var BsRGB = (Bbyte1AsDec + Bbyte2AsDec)/255



var R = if(RsRGB <= 0.03928, RsRGB/12.92, ((RsRGB + 0.055)/1.055)^2.4)

var G = if(GsRGB <= 0.03928, GsRGB/12.92, ((GsRGB + 0.055)/1.055)^2.4)

var B = if(BsRGB <= 0.03928, BsRGB/12.92, ((BsRGB + 0.055)/1.055)^2.4)



var relativeLuminance = 0.2126 * R + 0.7152 * G + 0.0722 * B

return if(relativeLuminance > 0.5, DarkOption, LightOption)



Reply · Report Post