Last active
March 2, 2025 01:12
-
-
Save bjulius/ad41c06e1b506a318a1895ee5b65dd80 to your computer and use it in GitHub Desktop.
Power BI Automatic Font Color Selection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CF Autoformat Font = | |
// based on Ed Freeman's blog entry// https://endjin.com/blog/2020/06/how-to-dynamically-choose-the-correct-font-colour-based-on-a-background-colour-in-power-bi-tables | |
// 1. Grab the background colour for the current row (you will need to change the [CF Rank] measure to whatever measure returns your conditional formatting background color hex codes | |
VAR selectedColour = [CF Rank] | |
// 2. Extract the hexadecimal value for each digit in each colour couplet, and translate to the decimal representation of that value | |
VAR redDig1 = MID(selectedColour, 2, 1) | |
VAR redDig1Number = SWITCH(redDig1,"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) | |
VAR redDig2 = MID(selectedColour, 3, 1) | |
VAR redDig2Number = SWITCH(redDig2,"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) | |
VAR greenDig1 = MID(selectedColour, 4, 1) | |
VAR greenDig1Number = SWITCH(greenDig1,"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) | |
VAR greenDig2 = MID(selectedColour, 5, 1) | |
VAR greenDig2Number = SWITCH(greenDig2,"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) | |
VAR blueDig1 = MID(selectedColour, 6, 1) | |
VAR blueDig1Number = SWITCH(blueDig1,"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) | |
VAR blueDig2 = MID(selectedColour, 7, 1) | |
VAR blueDig2Number = SWITCH(blueDig2,"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) | |
// 3. Assign the value of the Gamma exponent | |
VAR gamma = 2.2 | |
// 4. Calculate the RGB values and normalize | |
VAR redNumber = ((redDig1Number * 16) + redDig2Number) / 255 | |
VAR greenNumber = ((greenDig1Number * 16) + greenDig2Number) / 255 | |
VAR blueNumber = ((blueDig1Number * 16) + blueDig2Number) / 255 | |
// 5. Apply calculation as per Stack Exchange answer | |
VAR luminance = (0.2126 * POWER(redNumber, gamma)) + (0.7152 * POWER(greenNumber, gamma)) + (0.0722 * POWER(blueNumber, gamma)) | |
// 6. If the luminance is greater than 0.5, return "Black". Else return "White". | |
RETURN | |
SWITCH(TRUE(), | |
selectedColour = "Transparent", "Black", | |
ISBLANK( selectedColour ), "Black", | |
luminance > 0.5, "Black", | |
"White" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment