pub fn fit_image_dimensions(
img_width: u32,
img_height: u32,
max_width: f64,
max_height: f64,
) -> (f64, f64) {
if img_width == 0 || img_height == 0 {
return (0.0, 0.0);
}
let ratio = img_width as f64 / img_height as f64;
let w_from_h = max_height * ratio;
if w_from_h <= max_width {
(w_from_h, max_height)
} else {
let h_from_w = max_width / ratio;
(max_width, h_from_w)
}
}
pub fn centered_image_x(margin_left: f64, content_width: f64, image_width: f64) -> f64 {
margin_left + (content_width - image_width).max(0.0) / 2.0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_zero_dimensions() {
assert_eq!(fit_image_dimensions(0, 100, 200.0, 200.0), (0.0, 0.0));
assert_eq!(fit_image_dimensions(100, 0, 200.0, 200.0), (0.0, 0.0));
}
#[test]
fn test_square_image_in_square_box() {
let (w, h) = fit_image_dimensions(500, 500, 100.0, 100.0);
assert!((w - 100.0).abs() < 0.001);
assert!((h - 100.0).abs() < 0.001);
}
}