Alpha blending and compositing in (optionally) zero-dependency Rust.
There are three pieces:
- A
CompositeModedecides how much of the source and destination survive. These are the Porter-Duff operators. - A
BlendModedecides how their colors are mixed. These are the W3C separable blend modes. - A
Compositepairs 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.
cargo run --example porter-duff --features bytemuckA blue square and a red square, each 50% transparent, overlapping in the middle.
Clear![]() |
Source![]() |
Destination![]() |
SourceOver![]() |
DestinationOver![]() |
SourceIn![]() |
DestinationIn![]() |
SourceOut![]() |
DestinationOut![]() |
SourceAtop![]() |
DestinationAtop![]() |
Xor![]() |
Plus![]() |
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.
This project uses just to run commands the same way as the CI:
cargo just checkto check formatting and lints.cargo just coverageto generate and preview code coverage.cargo just docto generate and preview docs.cargo just testto run tests.
For a full list of commands, see the Justfile.
























