In this guide, you will learn how to manually refine color contrast using the
MCU contrast library. For optimal color contrast, we recommend using the DynamicColor and DynamicScheme features in your production.
To measure the contrast of two colors, use the ratioOfTones method on the
tones (L*) of the two colors.
The tone of an HCT color is the tone component. The tone of an ARGB color can
be obtained by ColorUtils.lstarFromArgb method.
Dart
1
final contrastRatio = Contrast.ratioOfTones(hct1.tone, hct2.tone);
1 2 3
final tone1 = ColorUtils.lstarFromArgb(argb1); final tone2 = ColorUtils.lstarFromArgb(argb2); final contrastRatio = Contrast.ratioOfTones(tone1, tone2);
let contrastRatio =Contrast.ratioOfTones(hct1.tone, hct2.tone)
1 2 3
let tone1 =ColorUtils.lstarFromArgb(argb1) let tone2 =ColorUtils.lstarFromArgb(argb2) let contrastRatio =Contrast.ratioOfTones(tone1, tone2)
Obtaining well-contrasting colors
The functions darker and lighter (and their variants darkerUnsafe and lighterUnsafe) allow one to obtain tones that contrast well against the tone of a given color.
The functions darker and lighter will return -1 if the required contrast
cannot be reached, whereas darkerUnsafe and lighterUnsafe will return 0
(tone of black) and 100 (tone of white), respectively, making the contrast
ratio as high as possible.
The word “unsafe” in the names means they may return a color without
guaranteeing contrast ratio. These functions do not crash but their output
colors may not meet accessibility standards.
Dart
1 2 3 4 5 6 7 8 9 10 11
final original = ColorUtils.lstarFromArgb(0xFF00AA00); // 60.56
final darker = Contrast.darker(original, 3.0); // 29.63 final lighter = Contrast.lighter(original, 3.0); // 98.93 final darkerUnsafe = Contrast.darkerUnsafe(original, 3.0); // 29.63 final lighterUnsafe = Contrast.lighterUnsafe(original, 3.0); // 98.93
final darker = Contrast.darker(original, 7.0); // -1.0 final lighter = Contrast.lighter(original, 7.0); // -1.0 final darkerUnsafe = Contrast.darkerUnsafe(original, 7.0); // 0.0 final lighterUnsafe = Contrast.lighterUnsafe(original, 7.0); // 100.0