calculateContrast function
Calculates contrast ratio of given backgroundColor
and foregroundColor
.
The ratio will be in range from 0 to 21. Typically the ratio starts at 1, but in this implementation we do use color's opacity into account: if the color's opacity is 0, meaning full transparency, the ratio is considered 0:1.
An order in which colors to compare are provided do not affect resulting contrast ratio.
Implementation
num calculateContrast(Color backgroundColor, Color foregroundColor) {
final backgroundLuminance = backgroundColor.computeLuminance();
final foregroundLuminance = foregroundColor.computeLuminance();
final lighterColorLuminance = backgroundLuminance > foregroundLuminance
? backgroundLuminance
: foregroundLuminance;
final darkerColorLuminance = backgroundLuminance < foregroundLuminance
? backgroundLuminance
: foregroundLuminance;
final opacityUnawareContrast =
(lighterColorLuminance + 0.05) / (darkerColorLuminance + 0.05);
return opacityUnawareContrast *
foregroundColor.opacity *
backgroundColor.opacity;
}