7

I would like to basically add two colors together as if I were to do the following with a Canvas object:

canvas.drawPaint(Paint()..color = colorB);
canvas.drawPaint(Paint()..color = colorA);

Essentially, I have a background color colorA and another color colorB. I want to get a combinedColor that would be the result from painting colorA onto colorB but without using the canvas.

I tried the following, but it is not implemented:

final combinedColor = colorA + colorB;

For example, if I have a semi-transparent colorA and another color that I want to paint colorA on, the other color should act as a background, i.e. as if it had full opacity itself - basically the way you would expect.

How do I add together colors like this?

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402

1 Answers1

21

I happened to find a method for this in the Color class:

Color.alphaBlend

final colorC = Color.alphaBlend(colorA, colorB);

alphaBlend allows you to combine two colors, where the first parameter is the foreground color and the second is the background color. So here, colorA is the foreground and colorB the background color.

operator +

The code sample from the question can be made working by creating an extension:

extension on Color {
  Color operator +(Color other) => Color.alphaBlend(this, other);
}

Now, the following code will work:

final combinedColor = colorA + addendColor;

Note that the way I created the extension, the addend (here addendColor) will be the background. You can change this by reversing (this, other) to (other, this).

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402