Skip to content

Commit 6af80e3

Browse files
committed
color: Add withFadedAlpha helper
This adds a new helper on `ColorExtension` following a similar naming and documentation style as other method like `withValues`. The motivation for this is to support a faded effect applies to colors that are possibly already transparent (i.e. have a non-one alpha channel value). Signed-off-by: Zixuan James Li <[email protected]>
1 parent 79fc2c2 commit 6af80e3

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

lib/widgets/color.dart

+9
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,13 @@ extension ColorExtension on Color {
3838
((g * 255.0).round() & 0xff) << 8 |
3939
((b * 255.0).round() & 0xff) << 0;
4040
}
41+
42+
/// Makes a copy of this color with the alpha channel multiplied by `factor`.
43+
///
44+
/// `factor` must not be less than 0 or greater than 1.
45+
Color withFadedAlpha(double factor) {
46+
assert(factor >= 0);
47+
assert(factor <= 1);
48+
return withValues(alpha: a * factor);
49+
}
4150
}

test/widgets/color_test.dart

+11
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import 'dart:ui';
22

33
import 'package:checks/checks.dart';
4+
import 'package:flutter_checks/flutter_checks.dart';
45
import 'package:test/scaffolding.dart';
56
import 'package:zulip/widgets/color.dart';
67

@@ -14,5 +15,15 @@ void main() {
1415
check(Color(testCase).argbInt).equals(testCase);
1516
}
1617
});
18+
19+
test('withFadedAlpha smoke', () {
20+
const color = Color.fromRGBO(100, 200, 100, 0.5);
21+
22+
check(color.withFadedAlpha(0.5))
23+
.isSameColorAs(color.withValues(alpha: 0.25));
24+
25+
check(() => color.withFadedAlpha(1.1)).throws<AssertionError>();
26+
check(() => color.withFadedAlpha(-0.1)).throws<AssertionError>();
27+
});
1728
});
1829
}

0 commit comments

Comments
 (0)