alphaBlend static method

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

static Color alphaBlend(Color foreground, Color background) {
  assert(foreground.colorSpace == background.colorSpace);
  assert(foreground.colorSpace != ColorSpace.extendedSRGB);
  final double alpha = foreground.a;
  if (alpha == 0) { // Foreground completely transparent.
    return background;
  }
  final double invAlpha = 1 - alpha;
  double backAlpha = background.a;
  if (backAlpha == 1) { // Opaque background case
    return Color.from(
      alpha: 1,
      red: alpha * foreground.r + invAlpha * background.r,
      green: alpha * foreground.g + invAlpha * background.g,
      blue: alpha * foreground.b + invAlpha * background.b,
      colorSpace: foreground.colorSpace,
    );
  } else { // General case
    backAlpha = backAlpha * invAlpha;
    final double outAlpha = alpha + backAlpha;
    assert(outAlpha != 0);
    return Color.from(
      alpha: outAlpha,
      red: (foreground.r * alpha + background.r * backAlpha) / outAlpha,
      green: (foreground.g * alpha + background.g * backAlpha) / outAlpha,
      blue: (foreground.b * alpha + background.b * backAlpha) / outAlpha,
      colorSpace: foreground.colorSpace,
    );
  }
}