Skip to content

Instantly share code, notes, and snippets.

@TheZoc
Created November 26, 2019 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheZoc/f7b1f158a14381bb19a11e65457a0992 to your computer and use it in GitHub Desktop.
Save TheZoc/f7b1f158a14381bb19a11e65457a0992 to your computer and use it in GitHub Desktop.
Qt QML High Contrast functions
// I wrote those for a dialog in QML that needed to keep high contrast while the background color could be customized
// by the user. I"m keeping it here in case I need it in the future :)
/**
* Calculates the relative luminance of given color
* Reference: https://www.w3.org/TR/WCAG20/#relativeluminancedef
*
* @param {color} color Color to calculate the relative luminance.
* @return Luminance, as a real between 0 and 1
*/
function relativeColorLuminance(color)
{
const r = color.r <= 0.03928 ? color.r / 12.92 : Math.pow((color.r + 0.055) / 1.055, 2.4);
const g = color.g <= 0.03928 ? color.g / 12.92 : Math.pow((color.g + 0.055) / 1.055, 2.4);
const b = color.b <= 0.03928 ? color.b / 12.92 : Math.pow((color.b + 0.055) / 1.055, 2.4);
return r * 0.2126 + g * 0.7152 + b * 0.0722;
}
/**
* Calculates the contrast ratio between two given colors
* Reference: https://medium.muz.li/the-science-of-color-contrast-an-expert-designers-guide-33e84c41d156
*
* @param {color} color1 First color.
* @param {color} color2 Second color.
*
* @return {real} Color Contrast Ratio between color1 and color2.
*/
function colorContrast(color1, color2)
{
var color1Luminance = relativeColorLuminance(color1);
var color2Luminance = relativeColorLuminance(color2);
var relativeContrast;
if(color1Luminance < color2Luminance)
relativeContrast = (color2Luminance + 0.05) / (color1Luminance + 0.05)
else
relativeContrast = (color1Luminance + 0.05) / (color2Luminance + 0.05)
return relativeContrast;
}
/**
* Returns a high contrast color between two options
* Given a color, and optionally a default color and an alternate color, returns the default color if it has
* at least 7:1 contrast ratio with color, otherwise, returns the alternate color.
* Reference://www.w3.org/TR/WCAG20-TECHS/G17.html - 7:1 contrast ratio
*
* @param {color} color Color to be tested against defaultColor.
* @param {color} defaultColor Default color returned, if ratio with color is at least 7:1 (or higher).
* @param {color} alternateColor Alternate color to be returned, if contrast ratio between color and defaultColor is lesser than 7:1.
*
* @return {real} ReturnsdefaultColor if ratio with color is at least 7:1 (or higher), otherwise returns alternateColor.
*/
function getHighContrastColor(color, defaultColor = Material.foreground, alternateColor = Material.background)
{
return (colorContrast(color, defaultColor) >= 7) ? defaultColor : alternateColor;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment