Color.alphaBlend constructor

Color.alphaBlend(
  1. Color foreground,
  2. Color background
)

Combine the foreground color as a transparent color over top of a background color, and return the resulting combined color.

This uses standard alpha blending ("SRC over DST") rules to produce a blended color from two colors. This can be used as a performance enhancement when trying to avoid needless alpha blending compositing operations for two things that are solid colors with the same shape, but overlay each other: instead, just paint one with the combined color.

Implementation

factory Color.alphaBlend(Color foreground, Color background) {
  final int alpha = foreground.alpha;
  if (alpha == 0x00) {
    // Foreground completely transparent.
    return background;
  }
  final int invAlpha = 0xff - alpha;
  int backAlpha = background.alpha;
  if (backAlpha == 0xff) {
    // Opaque background case
    return Color.fromARGB(
      0xff,
      (alpha * foreground.red + invAlpha * background.red) ~/ 0xff,
      (alpha * foreground.green + invAlpha * background.green) ~/ 0xff,
      (alpha * foreground.blue + invAlpha * background.blue) ~/ 0xff,
    );
  } else {
    // General case
    backAlpha = (backAlpha * invAlpha) ~/ 0xff;
    final int outAlpha = alpha + backAlpha;
    assert(outAlpha != 0x00, 'outAlpha must not be transparent');
    return Color.fromARGB(
      outAlpha,
      (foreground.red * alpha + background.red * backAlpha) ~/ outAlpha,
      (foreground.green * alpha + background.green * backAlpha) ~/ outAlpha,
      (foreground.blue * alpha + background.blue * backAlpha) ~/ outAlpha,
    );
  }
}