Skip to content

Commit 79d682e

Browse files
committed
A Color.fromRGBO
Sometimes it is convenient to construct a color from an opacity rather than an alpha value. Unfortunately, this constructor cannot be const because there's no const way to convert from a double to the internal representation of a Color, which is an int. Fixes flutter/flutter#5205
1 parent 6c5315c commit 79d682e

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

‎lib/ui/painting.dart‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,31 @@ class Color {
1919
const Color(int value) : value = value & 0xFFFFFFFF;
2020

2121
/// Construct a color from the lower 8 bits of four integers.
22+
///
23+
/// * `a` is the alpha value, with 0 being transparent and 255 being fully
24+
/// opaque.
25+
/// * `r` is [red], from 0 to 255.
26+
/// * `g` is [red], from 0 to 255.
27+
/// * `b` is [red], from 0 to 255.
2228
const Color.fromARGB(int a, int r, int g, int b) :
2329
value = ((((a & 0xff) << 24) |
2430
((r & 0xff) << 16) |
2531
((g & 0xff) << 8) |
2632
((b & 0xff) << 0)) & 0xFFFFFFFF);
2733

34+
/// Create a color from red, green, blue, and opacity.
35+
///
36+
/// * `opacity` is alpha channel of this color as a double, with 0.0 being
37+
/// transparent and 1.0 being fully opaque.
38+
/// * `r` is [red], from 0 to 255.
39+
/// * `g` is [red], from 0 to 255.
40+
/// * `b` is [red], from 0 to 255.
41+
Color.fromRGBO(int r, int g, int b, double opacity) :
42+
value = (((((opacity * 0xff).round().clamp(0, 0xff) & 0xff) << 24) |
43+
((r & 0xff) << 16) |
44+
((g & 0xff) << 8) |
45+
((b & 0xff) << 0)) & 0xFFFFFFFF);
46+
2847
/// A 32 bit value representing this color.
2948
///
3049
/// Bits 24-31 are the alpha value.
@@ -34,9 +53,15 @@ class Color {
3453
final int value;
3554

3655
/// The alpha channel of this color in an 8 bit value.
56+
///
57+
/// A value of 0 means this color is fully transparent. A value of 255 means
58+
/// this color is fully opaque.
3759
int get alpha => (0xff000000 & value) >> 24;
3860

3961
/// The alpha channel of this color as a double.
62+
///
63+
/// A value of 0.0 means this color is fully transparent. A value of 1.0 means
64+
/// this color is fully opaque.
4065
double get opacity => alpha / 0xFF;
4166

4267
/// The red channel of this color in an 8 bit value.

0 commit comments

Comments
 (0)