diff --git a/Cargo.lock b/Cargo.lock index d773900c9c1..9453d2070c6 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 6b46bc1062c..0fc5546453a 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 807aa7a545b..07c8f9ca206 100644 --- a/crates/ecolor/src/color32.rs +++ b/crates/ecolor/src/color32.rs @@ -235,4 +235,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( + lerp((self[0] as f32)..=(other[0] as f32), t).round() as u8, + lerp((self[1] as f32)..=(other[1] as f32), t).round() as u8, + lerp((self[2] as f32)..=(other[2] as f32), t).round() as u8, + lerp((self[3] as f32)..=(other[3] as f32), t).round() as u8, + ) + } } diff --git a/crates/egui_demo_lib/src/rendering_test.rs b/crates/egui_demo_lib/src/rendering_test.rs index 63078651ffd..54a4cfd5670 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, - ) -}