Created
July 11, 2018 19:33
-
-
Save aab29/d8c5e94093ce7f8e035874344d24ff41 to your computer and use it in GitHub Desktop.
Using Dart's generator functions to calculate the blended color values in a horizontal gradient
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Color { | |
| final double red; | |
| final double green; | |
| final double blue; | |
| const Color(this.red, this.green, this.blue); | |
| static double blendedChannel(double leftChannel, double rightChannel, double progress) => | |
| leftChannel * (1.0 - progress) + rightChannel * progress; | |
| @override | |
| String toString() => | |
| "(${red.toStringAsFixed(2)}, ${green.toStringAsFixed(2)}, ${blue.toStringAsFixed(2)})"; | |
| } | |
| Iterable<Color> gradient(Color leftColor, Color rightColor, {int blendsCount = 7}) sync* { | |
| for (var colorIndex = 0; colorIndex < blendsCount; colorIndex++) { | |
| var progress = colorIndex / (blendsCount - 1); | |
| var red = Color.blendedChannel(leftColor.red, rightColor.red, progress); | |
| var green = Color.blendedChannel(leftColor.green, rightColor.green, progress); | |
| var blue = Color.blendedChannel(leftColor.blue, rightColor.blue, progress); | |
| yield new Color(red, green, blue); | |
| } | |
| } | |
| void main() { | |
| var leftColor = new Color(1.0, 0.0, 0.0); | |
| var rightColor = new Color(0.0, 1.0, 0.5); | |
| var generator = gradient(leftColor, rightColor); | |
| for (var color in generator) { | |
| print(color); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment