From 204c4773d5fbe3c5456a9789c6282ad51bcc32b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 15 May 2025 20:37:56 +0200 Subject: [PATCH] Add `expand` method to `image` widget --- widget/src/image.rs | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/widget/src/image.rs b/widget/src/image.rs index e94213a0..80ebd721 100644 --- a/widget/src/image.rs +++ b/widget/src/image.rs @@ -64,6 +64,7 @@ pub struct Image { rotation: Rotation, opacity: f32, scale: f32, + expand: bool, } impl Image { @@ -78,6 +79,7 @@ impl Image { rotation: Rotation::default(), opacity: 1.0, scale: 1.0, + expand: false, } } @@ -93,6 +95,19 @@ impl Image { self } + /// Sets whether the [`Image`] should try to fill as much space + /// available as possible while keeping aspect ratio and without + /// allocating extra space in any axis with a [`Length::Shrink`] + /// sizing strategy. + /// + /// This is similar to using [`Length::Fill`] for both the + /// [`width`](Self::width) and the [`height`](Self::height), + /// but without the downside of blank space. + pub fn expand(mut self, expand: bool) -> Self { + self.expand = expand; + self + } + /// Sets the [`ContentFit`] of the [`Image`]. /// /// Defaults to [`ContentFit::Contain`] @@ -141,6 +156,7 @@ pub fn layout( height: Length, content_fit: ContentFit, rotation: Rotation, + expand: bool, ) -> layout::Node where Renderer: image::Renderer, @@ -154,20 +170,24 @@ where let rotated_size = rotation.apply(image_size); // The size to be available to the widget prior to `Shrink`ing - let raw_size = limits.resolve(width, height, rotated_size); + let bounds = if expand { + limits.max() + } else { + limits.resolve(width, height, rotated_size) + }; // The uncropped size of the image when fit to the bounds above - let full_size = content_fit.fit(rotated_size, raw_size); + let full_size = content_fit.fit(rotated_size, bounds); // Shrink the widget to fit the resized image, if requested let final_size = Size { width: match width { - Length::Shrink => f32::min(raw_size.width, full_size.width), - _ => raw_size.width, + Length::Shrink => f32::min(bounds.width, full_size.width), + _ => bounds.width, }, height: match height { - Length::Shrink => f32::min(raw_size.height, full_size.height), - _ => raw_size.height, + Length::Shrink => f32::min(bounds.height, full_size.height), + _ => bounds.height, }, }; @@ -309,6 +329,7 @@ where self.height, self.content_fit, self.rotation, + self.expand, ) }