# alpha-blend
Alpha blending and compositing in (optionally) zero-dependency Rust.
[](https://github.com/crates-lurey-io/alpha-blend/actions/workflows/test.yml)
[](https://github.com/crates-lurey-io/alpha-blend/actions/workflows/docs.yml)
[](https://crates.io/crates/alpha-blend)
[](https://codecov.io/gh/crates-lurey-io/alpha-blend)
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.
```rust
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
```sh
cargo run --example porter-duff --features bytemuck
```
A blue square and a red square, each 50% transparent, overlapping in the middle.
### Compositing operators
| `Clear`<br> | `Source`<br> | `Destination`<br> |
| `SourceOver`<br> | `DestinationOver`<br> | `SourceIn`<br> |
| `DestinationIn`<br> | `SourceOut`<br> | `DestinationOut`<br> |
| `SourceAtop`<br> | `DestinationAtop`<br> | `Xor`<br> |
| `Plus`<br> | | |
### Blend modes
| `Normal`<br> | `Multiply`<br> | `Screen`<br> |
| `Overlay`<br> | `Darken`<br> | `Lighten`<br> |
| `ColorDodge`<br> | `ColorBurn`<br> | `HardLight`<br> |
| `SoftLight`<br> | `Difference`<br> | `Exclusion`<br> |
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.
[`just`]: https://crates.io/crates/just
For a full list of commands, see the [`Justfile`](./Justfile).