diff --git a/Cargo.lock b/Cargo.lock index d773900c9..9453d2070 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1165,6 +1165,7 @@ dependencies = [ "cint", "color-hex", "document-features", + "emath", "serde", ] diff --git a/crates/ecolor/Cargo.toml b/crates/ecolor/Cargo.toml index 6b46bc106..0fc554645 100644 --- a/crates/ecolor/Cargo.toml +++ b/crates/ecolor/Cargo.toml @@ -30,6 +30,8 @@ default = [] [dependencies] +emath.workspace = true + #! ### Optional dependencies ## [`bytemuck`](https://docs.rs/bytemuck) enables you to cast `ecolor` types to `&[u8]`. diff --git a/crates/ecolor/src/color32.rs b/crates/ecolor/src/color32.rs index 807aa7a54..4e7153dc1 100644 --- a/crates/ecolor/src/color32.rs +++ b/crates/ecolor/src/color32.rs @@ -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). /// @@ -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)), + ) + } } diff --git a/crates/egui_demo_lib/src/rendering_test.rs b/crates/egui_demo_lib/src/rendering_test.rs index 63078651f..54a4cfd56 100644 --- a/crates/egui_demo_lib/src/rendering_test.rs +++ b/crates/egui_demo_lib/src/rendering_test.rs @@ -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(), ) @@ -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, - ) -}