Add `Color32::lerp_to_gamma` (#4627)

Add `lerp_to_gamma` utility function to `Color32`

---------

Co-authored-by: Emil Ernerfeldt <emil.ernerfeldt@gmail.com>
This commit is contained in:
Antoine Beyeler 2024-06-06 15:41:10 +02:00 committed by GitHub
parent 1f008fb730
commit 2545939c15
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 19 additions and 11 deletions

View File

@ -1165,6 +1165,7 @@ dependencies = [
"cint",
"color-hex",
"document-features",
"emath",
"serde",
]

View File

@ -30,6 +30,8 @@ default = []
[dependencies]
emath.workspace = true
#! ### Optional dependencies
## [`bytemuck`](https://docs.rs/bytemuck) enables you to cast `ecolor` types to `&[u8]`.

View File

@ -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)),
)
}
}

View File

@ -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,
)
}