alpha-blend 0.3.0

Alpha blending and compositing
Documentation

alpha-blend

Alpha blending and compositing in (optionally) zero-dependency Rust.

Test Docs Crates.io Version codecov

There are three pieces:

  • A CompositeMode decides how much of the source and destination survive. These are the Porter-Duff operators.
  • A BlendMode decides how their colors are mixed. These are the W3C separable blend modes.
  • A Composite pairs the two. Either half can be used on its own, in which case the other takes its default.
use alpha_blend::{BlendMode, Composite, CompositeMode, RgbaBlend, rgba::U8x4Rgba};

let src = U8x4Rgba::new(255, 128, 0, 128);
let dst = U8x4Rgba::new(0, 64, 255, 255);

// Plain source-over.
let out = CompositeMode::SourceOver.apply(src, dst);

// Multiply, composited source-over.
let out = Composite::new(BlendMode::Multiply, CompositeMode::SourceOver).apply(src, dst);

Everything is generic over the Channel trait, so u8 and f32 pixels go through the same code at their own precision. Integer channels round to nearest, once per operation, from a widened intermediate: scale(255, 255) == 255, and repeated compositing does not drift darker.

Examples

cargo run --example porter-duff --features bytemuck

A blue square and a red square, each 50% transparent, overlapping in the middle.

Compositing operators

Clear Source Destination
SourceOver DestinationOver SourceIn
DestinationIn SourceOut DestinationOut
SourceAtop DestinationAtop Xor
Plus

Blend modes

Normal Multiply Screen
Overlay Darken Lighten
ColorDodge ColorBurn HardLight
SoftLight Difference Exclusion

The four non-separable modes (Hue, Saturation, Color, Luminosity) are not implemented; they operate on the whole RGB triple rather than one channel at a time.

Contributing

This project uses just to run commands the same way as the CI:

  • cargo just check to check formatting and lints.
  • cargo just coverage to generate and preview code coverage.
  • cargo just doc to generate and preview docs.
  • cargo just test to run tests.

For a full list of commands, see the Justfile.