Add luminance getter to Color (flutter/engine#4252)

* add luminance getter to color

* tests

* nit
This commit is contained in:
xster
2017-10-24 18:39:54 -07:00
committed by GitHub
parent 8d4218960d
commit 6618c30371
2 changed files with 37 additions and 0 deletions

View File

@@ -200,6 +200,27 @@ class Color {
return new Color.fromARGB(alpha, red, green, b);
}
// See <https://www.w3.org/TR/WCAG20/#relativeluminancedef>
static double _linearizeColorComponent(double component) {
if (component <= 0.03928)
return component / 12.92;
return math.pow((component + 0.055) / 1.055, 2.4);
}
/// Returns a brightness value between 0 for darkest and 1 for lightest.
///
/// Represents the relative luminance of the color. This value is computationally
/// expensive to calculate.
///
/// See <https://en.wikipedia.org/wiki/Relative_luminance>.
double computeLuminance() {
// See <https://www.w3.org/TR/WCAG20/#relativeluminancedef>
final double R = _linearizeColorComponent(red / 0xFF);
final double G = _linearizeColorComponent(green / 0xFF);
final double B = _linearizeColorComponent(blue / 0xFF);
return 0.2126 * R + 0.7152 * G + 0.0722 * B;
}
/// Linearly interpolate between two colors.
///
/// If either color is null, this function linearly interpolates from a

View File

@@ -77,4 +77,20 @@ void main() {
const Color(0xFFFFFFFF),
);
});
test('compute gray luminance', () {
// Each color component is at 20%.
final Color lightGray = const Color(0xFF333333);
// Relative luminance's formula is just the linearized color value for gray.
// ((0.2 + 0.055) / 1.055) ^ 2.4.
expect(lightGray.computeLuminance(), equals(0.033104766570885055));
});
test('compute color luminance', () {
final Color brightRed = const Color(0xFFFF3B30);
// 0.2126 * ((1.0 + 0.055) / 1.055) ^ 2.4 +
// 0.7152 * ((0.23137254902 +0.055) / 1.055) ^ 2.4 +
// 0.0722 * ((0.18823529411 + 0.055) / 1.055) ^ 2.4
expect(brightRed.computeLuminance(), equals(0.24601329637099723));
});
}