Skip to content

Commit

Permalink
Add and document and explicit toARGB32. (flutter#56329)
Browse files Browse the repository at this point in the history
  • Loading branch information
matanlurey authored Nov 6, 2024
1 parent ebb5ada commit 382fd1e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
22 changes: 20 additions & 2 deletions lib/ui/painting.dart
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,26 @@ class Color {
/// * Bits 16-23 are the red value.
/// * Bits 8-15 are the green value.
/// * Bits 0-7 are the blue value.
@Deprecated('Use component accessors like .r or .g.')
int get value {
@Deprecated('Use component accessors like .r or .g, or toARGB32 for an explicit conversion')
int get value => toARGB32();

/// Returns a 32-bit value representing this color.
///
/// Unlike accessing the floating point equivalent channels individually
/// ([a], [r], [g], [b]), this method is intentionally _lossy_, and scales
/// each channel using `(channel * 255.0).round() & 0xff`.
///
/// While useful for storing a 32-bit integer value, prefer accessing the
/// individual channels (and storing the double equivalent) where higher
/// precision is required.
///
/// The bits are assigned as follows:
///
/// * Bits 24-31 represents the [a] channel as an 8-bit unsigned integer.
/// * Bits 16-23 represents the [r] channel as an 8-bit unsigned integer.
/// * Bits 8-15 represents the [g] channel as an 8-bit unsigned integer.
/// * Bits 0-7 represents the [b] channel as an 8-bit unsigned integer.
int toARGB32() {
return _floatToInt8(a) << 24 |
_floatToInt8(r) << 16 |
_floatToInt8(g) << 8 |
Expand Down
5 changes: 3 additions & 2 deletions lib/web_ui/lib/painting.dart
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,15 @@ class Color {
return (x * 255.0).round() & 0xff;
}

int get value {
int get value => toARGB32();

int toARGB32() {
return _floatToInt8(a) << 24 |
_floatToInt8(r) << 16 |
_floatToInt8(g) << 8 |
_floatToInt8(b) << 0;
}


int get alpha => (0xff000000 & value) >> 24;

double get opacity => alpha / 0xFF;
Expand Down
5 changes: 5 additions & 0 deletions testing/dart/color_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,11 @@ void main() {
// Call base class member, make sure it uses overridden value.
expect(color.red, 0xE0);
});

test('toARGB32 converts to a 32-bit integer', () {
const Color color = Color.from(alpha: 0.1, red: 0.2, green: 0.3, blue: 0.4);
expect(color.toARGB32(), equals(0x1a334d66));
});
}

class DynamicColorClass extends Color {
Expand Down

0 comments on commit 382fd1e

Please sign in to comment.