diff --git a/engine/src/flutter/lib/ui/painting.dart b/engine/src/flutter/lib/ui/painting.dart index 623699a379..4387a32083 100644 --- a/engine/src/flutter/lib/ui/painting.dart +++ b/engine/src/flutter/lib/ui/painting.dart @@ -200,6 +200,27 @@ class Color { return new Color.fromARGB(alpha, red, green, b); } + // See + 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 . + double computeLuminance() { + // See + 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 diff --git a/engine/src/flutter/testing/dart/color_test.dart b/engine/src/flutter/testing/dart/color_test.dart index 33f57e85d4..7b39d5d7db 100644 --- a/engine/src/flutter/testing/dart/color_test.dart +++ b/engine/src/flutter/testing/dart/color_test.dart @@ -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)); + }); }