Skip to content

Commit

Permalink
Add Color32::lerp_to_gamma (#4627)
Browse files Browse the repository at this point in the history
Add `lerp_to_gamma` utility function to `Color32`

---------

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>
  • Loading branch information
abey79 and emilk committed Jun 6, 2024
1 parent 1f008fb commit 2545939
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 11 deletions.
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1165,6 +1165,7 @@ dependencies = [
"cint",
"color-hex",
"document-features",
"emath",
"serde",
]

Expand Down
2 changes: 2 additions & 0 deletions crates/ecolor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ default = []


[dependencies]
emath.workspace = true

#! ### Optional dependencies

## [`bytemuck`](https://docs.rs/bytemuck) enables you to cast `ecolor` types to `&[u8]`.
Expand Down
16 changes: 15 additions & 1 deletion crates/ecolor/src/color32.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::{gamma_u8_from_linear_f32, linear_f32_from_gamma_u8, linear_f32_from_linear_u8, Rgba};
use crate::{
fast_round, gamma_u8_from_linear_f32, linear_f32_from_gamma_u8, linear_f32_from_linear_u8, Rgba,
};

/// This format is used for space-efficient color representation (32 bits).
///
Expand Down Expand Up @@ -235,4 +237,16 @@ impl Color32 {
a as f32 / 255.0,
]
}

/// Lerp this color towards `other` by `t` in gamma space.
pub fn lerp_to_gamma(&self, other: Self, t: f32) -> Self {
use emath::lerp;

Self::from_rgba_premultiplied(
fast_round(lerp((self[0] as f32)..=(other[0] as f32), t)),
fast_round(lerp((self[1] as f32)..=(other[1] as f32), t)),
fast_round(lerp((self[2] as f32)..=(other[2] as f32), t)),
fast_round(lerp((self[3] as f32)..=(other[3] as f32), t)),
)
}
}
11 changes: 1 addition & 10 deletions crates/egui_demo_lib/src/rendering_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ impl Gradient {
(0..=n)
.map(|i| {
let t = i as f32 / n as f32;
lerp_color_gamma(left, right, t)
left.lerp_to_gamma(right, t)
})
.collect(),
)
Expand Down Expand Up @@ -634,12 +634,3 @@ fn mul_color_gamma(left: Color32, right: Color32) -> Color32 {
(left.a() as f32 * right.a() as f32 / 255.0).round() as u8,
)
}

fn lerp_color_gamma(left: Color32, right: Color32, t: f32) -> Color32 {
Color32::from_rgba_premultiplied(
lerp((left[0] as f32)..=(right[0] as f32), t).round() as u8,
lerp((left[1] as f32)..=(right[1] as f32), t).round() as u8,
lerp((left[2] as f32)..=(right[2] as f32), t).round() as u8,
lerp((left[3] as f32)..=(right[3] as f32), t).round() as u8,
)
}

0 comments on commit 2545939

Please sign in to comment.