Skip to content

Commit

Permalink
Add luminance getter to Color (flutter#4252)
Browse files Browse the repository at this point in the history
* add luminance getter to color

* tests

* nit
  • Loading branch information
xster authored Oct 25, 2017
1 parent 352e637 commit 28e0805
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/ui/painting.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions testing/dart/color_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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));
});
}

0 comments on commit 28e0805

Please sign in to comment.