From ca1fcdaf1454fd3febae8e6864c9a7dec04f41b1 Mon Sep 17 00:00:00 2001 From: Emi Simpson Date: Sat, 22 Jan 2022 20:09:35 -0500 Subject: Add support for `ContentFit` for `Image` --- core/src/image.rs | 119 +++++++++++++++++++++++++++++++++++++++++++++ core/src/lib.rs | 2 + examples/tour/src/main.rs | 98 +++++++++++++++++++++++++++++-------- native/src/lib.rs | 4 +- native/src/widget/image.rs | 66 +++++++++++++++++++------ src/widget.rs | 1 + 6 files changed, 252 insertions(+), 38 deletions(-) create mode 100644 core/src/image.rs diff --git a/core/src/image.rs b/core/src/image.rs new file mode 100644 index 00000000..97a9eb2c --- /dev/null +++ b/core/src/image.rs @@ -0,0 +1,119 @@ +//! Control the fit of some content (like an image) within a space + +use crate::Size; + +/// How the image should scale to fit the bounding box of the widget +/// +/// Each variant of this enum is a strategy that can be applied for resolving +/// differences in aspect ratio and size between the image being displayed and +/// the space its being displayed in. +/// +/// For an interactive demonstration of these properties as they are implemented +/// in CSS, see [Mozilla's docs][1], or run the `tour` example +/// +/// [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit +#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)] +pub enum ContentFit { + /// Scale as big as it can be without needing to crop or hide parts + /// + /// The image will be scaled (preserving aspect ratio) so that it just fits + /// within the window. This won't distort the image or crop/hide any edges, + /// but if the image doesn't fit perfectly, there may be whitespace on the + /// top/bottom or left/right. + /// + /// This is a great fit for when you need to display an image without losing + /// any part of it, particularly when the image itself is the focus of the + /// screen. + Contain, + + /// Scale the image to cover all of the bounding box, cropping if needed + /// + /// This doesn't distort the image, and it ensures that the widget's area is + /// completely covered, but it might crop off a bit of the edges of the + /// widget, particularly when there is a big difference between the aspect + /// ratio of the widget and the aspect ratio of the image. + /// + /// This is best for when you're using an image as a background, or to fill + /// space, and any details of the image around the edge aren't too + /// important. + Cover, + + /// Distort the image so the widget is 100% covered without cropping + /// + /// This stretches the image to fit the widget, without any whitespace or + /// cropping. However, because of the stretch, the image may look distorted + /// or elongated, particularly when there's a mismatch of aspect ratios. + Fill, + + /// Don't resize or scale the image at all + /// + /// This will not apply any transformations to the provided image, but also + /// means that unless you do the math yourself, the widget's area will not + /// be completely covered, or the image might be cropped. + /// + /// This is best for when you've sized the image yourself. + None, + + /// Scale the image down if it's too big for the space, but never scale it up + /// + /// This works much like [`Contain`](Self::Contain), except that if the + /// image would have been scaled up, it keeps its original resolution to + /// avoid the bluring that accompanies upscaling images. + ScaleDown, +} + +impl ContentFit { + /// Attempt to apply the given fit for a content size within some bounds + /// + /// The returned value is the recommended scaled size of the content. + pub fn fit(&self, content: Size, bounds: Size) -> Size { + let content_ar = content.width / content.height; + let bounds_ar = bounds.width / bounds.height; + + match self { + Self::Contain => { + if bounds_ar > content_ar { + Size { + width: content.width * bounds.height / content.height, + ..bounds + } + } else { + Size { + height: content.height * bounds.width / content.width, + ..bounds + } + } + } + Self::Cover => { + if bounds_ar < content_ar { + Size { + width: content.width * bounds.height / content.height, + ..bounds + } + } else { + Size { + height: content.height * bounds.width / content.width, + ..bounds + } + } + } + Self::Fill => bounds, + Self::None => content, + Self::ScaleDown => { + if bounds_ar > content_ar && bounds.height < content.height { + Size { + width: content.width * bounds.height / content.height, + ..bounds + } + } else if bounds.width < content.width { + Size { + height: content.height * bounds.width / content.width, + ..bounds + } + } else { + content + } + } + } + } +} diff --git a/core/src/lib.rs b/core/src/lib.rs index 2a4e6158..0eac97c2 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -22,6 +22,7 @@ pub mod time; mod background; mod color; mod font; +mod image; mod length; mod padding; mod point; @@ -33,6 +34,7 @@ pub use alignment::Alignment; pub use background::Background; pub use color::Color; pub use font::Font; +pub use image::ContentFit; pub use length::Length; pub use padding::Padding; pub use point::Point; diff --git a/examples/tour/src/main.rs b/examples/tour/src/main.rs index d4b41310..63062e7c 100644 --- a/examples/tour/src/main.rs +++ b/examples/tour/src/main.rs @@ -1,7 +1,8 @@ use iced::{ - alignment, button, scrollable, slider, text_input, Button, Checkbox, Color, - Column, Container, Element, Image, Length, Radio, Row, Sandbox, Scrollable, - Settings, Slider, Space, Text, TextInput, Toggler, + alignment, button, image::ContentFit, scrollable, slider, text_input, + Button, Checkbox, Color, Column, Container, Element, Image, Length, Radio, + Row, Sandbox, Scrollable, Settings, Slider, Space, Text, TextInput, + Toggler, }; pub fn main() -> iced::Result { @@ -139,7 +140,8 @@ impl Steps { can_continue: false, }, Step::Image { - width: 300, + height: 200, + current_fit: ContentFit::Contain, slider: slider::State::new(), }, Step::Scrollable, @@ -213,8 +215,9 @@ enum Step { can_continue: bool, }, Image { - width: u16, + height: u16, slider: slider::State, + current_fit: ContentFit, }, Scrollable, TextInput { @@ -234,7 +237,8 @@ pub enum StepMessage { TextSizeChanged(u16), TextColorChanged(Color), LanguageSelected(Language), - ImageWidthChanged(u16), + ImageHeightChanged(u16), + ImageFitSelected(ContentFit), InputChanged(String), ToggleSecureInput(bool), DebugToggled(bool), @@ -279,9 +283,14 @@ impl<'a> Step { *spacing = new_spacing; } } - StepMessage::ImageWidthChanged(new_width) => { - if let Step::Image { width, .. } = self { - *width = new_width; + StepMessage::ImageHeightChanged(new_height) => { + if let Step::Image { height, .. } = self { + *height = new_height; + } + } + StepMessage::ImageFitSelected(fit) => { + if let Step::Image { current_fit, .. } = self { + *current_fit = fit; } } StepMessage::InputChanged(new_value) => { @@ -346,7 +355,11 @@ impl<'a> Step { color_sliders, color, } => Self::text(size_slider, *size, color_sliders, *color), - Step::Image { width, slider } => Self::image(*width, slider), + Step::Image { + height, + slider, + current_fit, + } => Self::image(*height, slider, *current_fit), Step::RowsAndColumns { layout, spacing_slider, @@ -574,23 +587,45 @@ impl<'a> Step { } fn image( - width: u16, + height: u16, slider: &'a mut slider::State, + current_fit: ContentFit, ) -> Column<'a, StepMessage> { + const FIT_MODES: [(ContentFit, &str); 5] = [ + (ContentFit::Contain, "Contain"), + (ContentFit::Cover, "Cover"), + (ContentFit::Fill, "Fill"), + (ContentFit::None, "None"), + (ContentFit::ScaleDown, "Only Scale Down"), + ]; + + let mode_selector = FIT_MODES.iter().fold( + Column::new().padding(10).spacing(20), + |choices, (mode, name)| { + choices.push(Radio::new( + *mode, + *name, + Some(current_fit), + StepMessage::ImageFitSelected, + )) + }, + ); + Self::container("Image") - .push(Text::new("An image that tries to keep its aspect ratio.")) - .push(ferris(width)) + .push(Text::new("Pictures of things in all shapes and sizes!")) + .push(logo(height, current_fit)) .push(Slider::new( slider, - 100..=500, - width, - StepMessage::ImageWidthChanged, + 50..=500, + height, + StepMessage::ImageHeightChanged, )) .push( - Text::new(format!("Width: {} px", width.to_string())) + Text::new(format!("Height: {} px", height)) .width(Length::Fill) .horizontal_alignment(alignment::Horizontal::Center), ) + .push(mode_selector) } fn scrollable() -> Column<'a, StepMessage> { @@ -613,7 +648,7 @@ impl<'a> Step { .horizontal_alignment(alignment::Horizontal::Center), ) .push(Column::new().height(Length::Units(4096))) - .push(ferris(300)) + .push(ferris(200)) .push( Text::new("You made it!") .width(Length::Fill) @@ -699,6 +734,7 @@ impl<'a> Step { } } +/// Passing fit=None defaults to ContentFit::Contain fn ferris<'a>(width: u16) -> Container<'a, StepMessage> { Container::new( // This should go away once we unify resource loading on native @@ -708,10 +744,32 @@ fn ferris<'a>(width: u16) -> Container<'a, StepMessage> { } else { Image::new(format!( "{}/images/ferris.png", - env!("CARGO_MANIFEST_DIR") + env!("CARGO_MANIFEST_DIR"), + )) + } + .width(Length::Units(width)) + .fit(ContentFit::Contain), + ) + .width(Length::Fill) + .center_x() +} + +/// Passing fit=None defaults to ContentFit::Contain +fn logo<'a>(height: u16, fit: ContentFit) -> Container<'a, StepMessage> { + Container::new( + // This should go away once we unify resource loading on native + // platforms + if cfg!(target_arch = "wasm32") { + Image::new("tour/images/logo.png") + } else { + Image::new(format!( + "{}/images/logo.png", + env!("CARGO_MANIFEST_DIR"), )) } - .width(Length::Units(width)), + .width(Length::Fill) + .height(Length::Units(height)) + .fit(fit), ) .width(Length::Fill) .center_x() diff --git a/native/src/lib.rs b/native/src/lib.rs index 6d98f7d1..5c9c24c9 100644 --- a/native/src/lib.rs +++ b/native/src/lib.rs @@ -71,8 +71,8 @@ mod debug; pub use iced_core::alignment; pub use iced_core::time; pub use iced_core::{ - Alignment, Background, Color, Font, Length, Padding, Point, Rectangle, - Size, Vector, + Alignment, Background, Color, ContentFit, Font, Length, Padding, Point, + Rectangle, Size, Vector, }; pub use iced_futures::{executor, futures}; diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index b8fb662e..5ddc3642 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -5,7 +5,9 @@ pub use viewer::Viewer; use crate::image; use crate::layout; use crate::renderer; -use crate::{Element, Hasher, Layout, Length, Point, Rectangle, Size, Widget}; +use crate::{ + ContentFit, Element, Hasher, Layout, Length, Point, Rectangle, Size, Widget, +}; use std::hash::Hash; @@ -26,6 +28,7 @@ pub struct Image { handle: Handle, width: Length, height: Length, + fit: ContentFit, } impl Image { @@ -35,6 +38,7 @@ impl Image { handle: handle.into(), width: Length::Shrink, height: Length::Shrink, + fit: ContentFit::Contain, } } @@ -49,6 +53,13 @@ impl Image { self.height = height; self } + + /// Sets the image fit + /// + /// Defaults to [`ContentFit::Contain`] + pub fn fit(self, fit: ContentFit) -> Self { + Self { fit, ..self } + } } impl Widget for Image @@ -69,24 +80,32 @@ where renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { + // The raw w/h of the underlying image let (width, height) = renderer.dimensions(&self.handle); + let image_size = Size::new(width as f32, height as f32); - let aspect_ratio = width as f32 / height as f32; - - let mut size = limits + // The size to be available to the widget prior to `Shrink`ing + let raw_size = limits .width(self.width) .height(self.height) - .resolve(Size::new(width as f32, height as f32)); - - let viewport_aspect_ratio = size.width / size.height; - - if viewport_aspect_ratio > aspect_ratio { - size.width = width as f32 * size.height / height as f32; - } else { - size.height = height as f32 * size.width / width as f32; - } - - layout::Node::new(size) + .resolve(image_size); + + // The uncropped size of the image when fit to the bounds above + let full_size = self.fit.fit(image_size, raw_size); + + // Shrink the widget to fit the resized image, if requested + let final_size = Size { + width: match self.width { + Length::Shrink => f32::min(raw_size.width, full_size.width), + _ => raw_size.width, + }, + height: match self.height { + Length::Shrink => f32::min(raw_size.height, full_size.height), + _ => raw_size.height, + }, + }; + + layout::Node::new(final_size) } fn draw( @@ -97,7 +116,22 @@ where _cursor_position: Point, _viewport: &Rectangle, ) { - renderer.draw(self.handle.clone(), layout.bounds()); + // The raw w/h of the underlying image + let (width, height) = renderer.dimensions(&self.handle); + let image_size = Size::new(width as f32, height as f32); + + let adjusted_fit = self.fit.fit(image_size, layout.bounds().size()); + + renderer.with_layer(layout.bounds(), |renderer| { + renderer.draw( + self.handle.clone(), + Rectangle { + width: adjusted_fit.width, + height: adjusted_fit.height, + ..layout.bounds() + }, + ) + }) } fn hash_layout(&self, state: &mut Hasher) { diff --git a/src/widget.rs b/src/widget.rs index c619bcfa..d27e4c72 100644 --- a/src/widget.rs +++ b/src/widget.rs @@ -39,6 +39,7 @@ pub mod image { pub use crate::runtime::image::Handle; pub use crate::runtime::widget::image::viewer; pub use crate::runtime::widget::image::{Image, Viewer}; + pub use crate::runtime::ContentFit; } #[cfg_attr(docsrs, doc(cfg(feature = "svg")))] -- cgit From c6486978de7f47577c85ed18ccb28a760381d421 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 16 Feb 2022 17:28:04 +0700 Subject: Rename `image` module to `content_fit` in `iced_core` Since we are just exposing the `ContentFit` type and not the module `image` at all. --- core/src/content_fit.rs | 119 ++++++++++++++++++++++++++++++++++++++++++++++++ core/src/image.rs | 119 ------------------------------------------------ core/src/lib.rs | 4 +- 3 files changed, 121 insertions(+), 121 deletions(-) create mode 100644 core/src/content_fit.rs delete mode 100644 core/src/image.rs diff --git a/core/src/content_fit.rs b/core/src/content_fit.rs new file mode 100644 index 00000000..6bbedc7a --- /dev/null +++ b/core/src/content_fit.rs @@ -0,0 +1,119 @@ +//! Control the fit of some content (like an image) within a space. +use crate::Size; + +/// The strategy used to fit the contents of a widget to its bounding box. +/// +/// Each variant of this enum is a strategy that can be applied for resolving +/// differences in aspect ratio and size between the image being displayed and +/// the space its being displayed in. +/// +/// For an interactive demonstration of these properties as they are implemented +/// in CSS, see [Mozilla's docs][1], or run the `tour` example +/// +/// [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit +#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)] +pub enum ContentFit { + /// Scale as big as it can be without needing to crop or hide parts. + /// + /// The image will be scaled (preserving aspect ratio) so that it just fits + /// within the window. This won't distort the image or crop/hide any edges, + /// but if the image doesn't fit perfectly, there may be whitespace on the + /// top/bottom or left/right. + /// + /// This is a great fit for when you need to display an image without losing + /// any part of it, particularly when the image itself is the focus of the + /// screen. + Contain, + + /// Scale the image to cover all of the bounding box, cropping if needed. + /// + /// This doesn't distort the image, and it ensures that the widget's area is + /// completely covered, but it might crop off a bit of the edges of the + /// widget, particularly when there is a big difference between the aspect + /// ratio of the widget and the aspect ratio of the image. + /// + /// This is best for when you're using an image as a background, or to fill + /// space, and any details of the image around the edge aren't too + /// important. + Cover, + + /// Distort the image so the widget is 100% covered without cropping. + /// + /// This stretches the image to fit the widget, without any whitespace or + /// cropping. However, because of the stretch, the image may look distorted + /// or elongated, particularly when there's a mismatch of aspect ratios. + Fill, + + /// Don't resize or scale the image at all. + /// + /// This will not apply any transformations to the provided image, but also + /// means that unless you do the math yourself, the widget's area will not + /// be completely covered, or the image might be cropped. + /// + /// This is best for when you've sized the image yourself. + None, + + /// Scale the image down if it's too big for the space, but never scale it + /// up. + /// + /// This works much like [`Contain`](Self::Contain), except that if the + /// image would have been scaled up, it keeps its original resolution to + /// avoid the bluring that accompanies upscaling images. + ScaleDown, +} + +impl ContentFit { + /// Attempt to apply the given fit for a content size within some bounds. + /// + /// The returned value is the recommended scaled size of the content. + pub fn fit(&self, content: Size, bounds: Size) -> Size { + let content_ar = content.width / content.height; + let bounds_ar = bounds.width / bounds.height; + + match self { + Self::Contain => { + if bounds_ar > content_ar { + Size { + width: content.width * bounds.height / content.height, + ..bounds + } + } else { + Size { + height: content.height * bounds.width / content.width, + ..bounds + } + } + } + Self::Cover => { + if bounds_ar < content_ar { + Size { + width: content.width * bounds.height / content.height, + ..bounds + } + } else { + Size { + height: content.height * bounds.width / content.width, + ..bounds + } + } + } + Self::Fill => bounds, + Self::None => content, + Self::ScaleDown => { + if bounds_ar > content_ar && bounds.height < content.height { + Size { + width: content.width * bounds.height / content.height, + ..bounds + } + } else if bounds.width < content.width { + Size { + height: content.height * bounds.width / content.width, + ..bounds + } + } else { + content + } + } + } + } +} diff --git a/core/src/image.rs b/core/src/image.rs deleted file mode 100644 index 97a9eb2c..00000000 --- a/core/src/image.rs +++ /dev/null @@ -1,119 +0,0 @@ -//! Control the fit of some content (like an image) within a space - -use crate::Size; - -/// How the image should scale to fit the bounding box of the widget -/// -/// Each variant of this enum is a strategy that can be applied for resolving -/// differences in aspect ratio and size between the image being displayed and -/// the space its being displayed in. -/// -/// For an interactive demonstration of these properties as they are implemented -/// in CSS, see [Mozilla's docs][1], or run the `tour` example -/// -/// [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit -#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)] -pub enum ContentFit { - /// Scale as big as it can be without needing to crop or hide parts - /// - /// The image will be scaled (preserving aspect ratio) so that it just fits - /// within the window. This won't distort the image or crop/hide any edges, - /// but if the image doesn't fit perfectly, there may be whitespace on the - /// top/bottom or left/right. - /// - /// This is a great fit for when you need to display an image without losing - /// any part of it, particularly when the image itself is the focus of the - /// screen. - Contain, - - /// Scale the image to cover all of the bounding box, cropping if needed - /// - /// This doesn't distort the image, and it ensures that the widget's area is - /// completely covered, but it might crop off a bit of the edges of the - /// widget, particularly when there is a big difference between the aspect - /// ratio of the widget and the aspect ratio of the image. - /// - /// This is best for when you're using an image as a background, or to fill - /// space, and any details of the image around the edge aren't too - /// important. - Cover, - - /// Distort the image so the widget is 100% covered without cropping - /// - /// This stretches the image to fit the widget, without any whitespace or - /// cropping. However, because of the stretch, the image may look distorted - /// or elongated, particularly when there's a mismatch of aspect ratios. - Fill, - - /// Don't resize or scale the image at all - /// - /// This will not apply any transformations to the provided image, but also - /// means that unless you do the math yourself, the widget's area will not - /// be completely covered, or the image might be cropped. - /// - /// This is best for when you've sized the image yourself. - None, - - /// Scale the image down if it's too big for the space, but never scale it up - /// - /// This works much like [`Contain`](Self::Contain), except that if the - /// image would have been scaled up, it keeps its original resolution to - /// avoid the bluring that accompanies upscaling images. - ScaleDown, -} - -impl ContentFit { - /// Attempt to apply the given fit for a content size within some bounds - /// - /// The returned value is the recommended scaled size of the content. - pub fn fit(&self, content: Size, bounds: Size) -> Size { - let content_ar = content.width / content.height; - let bounds_ar = bounds.width / bounds.height; - - match self { - Self::Contain => { - if bounds_ar > content_ar { - Size { - width: content.width * bounds.height / content.height, - ..bounds - } - } else { - Size { - height: content.height * bounds.width / content.width, - ..bounds - } - } - } - Self::Cover => { - if bounds_ar < content_ar { - Size { - width: content.width * bounds.height / content.height, - ..bounds - } - } else { - Size { - height: content.height * bounds.width / content.width, - ..bounds - } - } - } - Self::Fill => bounds, - Self::None => content, - Self::ScaleDown => { - if bounds_ar > content_ar && bounds.height < content.height { - Size { - width: content.width * bounds.height / content.height, - ..bounds - } - } else if bounds.width < content.width { - Size { - height: content.height * bounds.width / content.width, - ..bounds - } - } else { - content - } - } - } - } -} diff --git a/core/src/lib.rs b/core/src/lib.rs index 0eac97c2..3eb9f659 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -21,8 +21,8 @@ pub mod time; mod background; mod color; +mod content_fit; mod font; -mod image; mod length; mod padding; mod point; @@ -33,8 +33,8 @@ mod vector; pub use alignment::Alignment; pub use background::Background; pub use color::Color; +pub use content_fit::ContentFit; pub use font::Font; -pub use image::ContentFit; pub use length::Length; pub use padding::Padding; pub use point::Point; -- cgit From 395eacfc103e3123a10bebe4a9330f7c126650a4 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 16 Feb 2022 17:35:28 +0700 Subject: Use a new clipping layer only when necessary in `Image::draw` --- native/src/widget/image.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index 5ddc3642..b253b1b8 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -121,8 +121,9 @@ where let image_size = Size::new(width as f32, height as f32); let adjusted_fit = self.fit.fit(image_size, layout.bounds().size()); + let bounds = layout.bounds(); - renderer.with_layer(layout.bounds(), |renderer| { + let render = |renderer: &mut Renderer| { renderer.draw( self.handle.clone(), Rectangle { @@ -131,7 +132,15 @@ where ..layout.bounds() }, ) - }) + }; + + if adjusted_fit.width > bounds.width + || adjusted_fit.height > bounds.height + { + renderer.with_layer(layout.bounds(), render); + } else { + render(renderer) + } } fn hash_layout(&self, state: &mut Hasher) { -- cgit From 8b5c9dfa71f770281ca277163c320571c39ee572 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 16 Feb 2022 17:37:24 +0700 Subject: Make documentation of `Image::fit` consistent --- native/src/widget/image.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index b253b1b8..f2b8ef2f 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -54,7 +54,7 @@ impl Image { self } - /// Sets the image fit + /// Sets the [`ContentFit`] of the [`Image`]. /// /// Defaults to [`ContentFit::Contain`] pub fn fit(self, fit: ContentFit) -> Self { -- cgit From 0aff444941f8b44b5a996dde4810ba6313f43a7e Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 16 Feb 2022 17:51:03 +0700 Subject: Rename `Image::fit` to `content_fit` ... just for consistency! --- examples/tour/src/main.rs | 4 ++-- native/src/widget/image.rs | 16 ++++++++++------ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/examples/tour/src/main.rs b/examples/tour/src/main.rs index 63062e7c..0c61add0 100644 --- a/examples/tour/src/main.rs +++ b/examples/tour/src/main.rs @@ -748,7 +748,7 @@ fn ferris<'a>(width: u16) -> Container<'a, StepMessage> { )) } .width(Length::Units(width)) - .fit(ContentFit::Contain), + .content_fit(ContentFit::Contain), ) .width(Length::Fill) .center_x() @@ -769,7 +769,7 @@ fn logo<'a>(height: u16, fit: ContentFit) -> Container<'a, StepMessage> { } .width(Length::Fill) .height(Length::Units(height)) - .fit(fit), + .content_fit(fit), ) .width(Length::Fill) .center_x() diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index f2b8ef2f..d83230f2 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -28,7 +28,7 @@ pub struct Image { handle: Handle, width: Length, height: Length, - fit: ContentFit, + content_fit: ContentFit, } impl Image { @@ -38,7 +38,7 @@ impl Image { handle: handle.into(), width: Length::Shrink, height: Length::Shrink, - fit: ContentFit::Contain, + content_fit: ContentFit::Contain, } } @@ -57,8 +57,11 @@ impl Image { /// Sets the [`ContentFit`] of the [`Image`]. /// /// Defaults to [`ContentFit::Contain`] - pub fn fit(self, fit: ContentFit) -> Self { - Self { fit, ..self } + pub fn content_fit(self, content_fit: ContentFit) -> Self { + Self { + content_fit, + ..self + } } } @@ -91,7 +94,7 @@ where .resolve(image_size); // The uncropped size of the image when fit to the bounds above - let full_size = self.fit.fit(image_size, raw_size); + let full_size = self.content_fit.fit(image_size, raw_size); // Shrink the widget to fit the resized image, if requested let final_size = Size { @@ -120,7 +123,8 @@ where let (width, height) = renderer.dimensions(&self.handle); let image_size = Size::new(width as f32, height as f32); - let adjusted_fit = self.fit.fit(image_size, layout.bounds().size()); + let adjusted_fit = + self.content_fit.fit(image_size, layout.bounds().size()); let bounds = layout.bounds(); let render = |renderer: &mut Renderer| { -- cgit From 6822d1d9f2c5b4fcbf65763c8edd091ac18a657e Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 16 Feb 2022 17:52:57 +0700 Subject: Center `Image` inside available bounds when possible --- native/src/widget/image.rs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index d83230f2..a2e7f765 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -6,7 +6,8 @@ use crate::image; use crate::layout; use crate::renderer; use crate::{ - ContentFit, Element, Hasher, Layout, Length, Point, Rectangle, Size, Widget, + ContentFit, Element, Hasher, Layout, Length, Point, Rectangle, Size, + Vector, Widget, }; use std::hash::Hash; @@ -128,14 +129,18 @@ where let bounds = layout.bounds(); let render = |renderer: &mut Renderer| { - renderer.draw( - self.handle.clone(), - Rectangle { - width: adjusted_fit.width, - height: adjusted_fit.height, - ..layout.bounds() - }, - ) + let offset = Vector::new( + (bounds.width - adjusted_fit.width).max(0.0) / 2.0, + (bounds.height - adjusted_fit.height).max(0.0) / 2.0, + ); + + let bounds = Rectangle { + width: adjusted_fit.width, + height: adjusted_fit.height, + ..layout.bounds() + }; + + renderer.draw(self.handle.clone(), bounds + offset) }; if adjusted_fit.width > bounds.width -- cgit From c910e239196655f3d5ba146aa3dc8da2b578ef8e Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 16 Feb 2022 17:58:51 +0700 Subject: Expose `ContentFit` in root --- examples/tour/src/main.rs | 7 +++---- src/lib.rs | 4 ++-- src/widget.rs | 1 - 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/examples/tour/src/main.rs b/examples/tour/src/main.rs index 0c61add0..9a675168 100644 --- a/examples/tour/src/main.rs +++ b/examples/tour/src/main.rs @@ -1,8 +1,7 @@ use iced::{ - alignment, button, image::ContentFit, scrollable, slider, text_input, - Button, Checkbox, Color, Column, Container, Element, Image, Length, Radio, - Row, Sandbox, Scrollable, Settings, Slider, Space, Text, TextInput, - Toggler, + alignment, button, scrollable, slider, text_input, Button, Checkbox, Color, + Column, Container, ContentFit, Element, Image, Length, Radio, Row, Sandbox, + Scrollable, Settings, Slider, Space, Text, TextInput, Toggler, }; pub fn main() -> iced::Result { diff --git a/src/lib.rs b/src/lib.rs index c8047d7f..b34bb72c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -221,6 +221,6 @@ pub use settings::Settings; pub use runtime::alignment; pub use runtime::futures; pub use runtime::{ - Alignment, Background, Color, Command, Font, Length, Point, Rectangle, - Size, Subscription, Vector, + Alignment, Background, Color, Command, ContentFit, Font, Length, Point, + Rectangle, Size, Subscription, Vector, }; diff --git a/src/widget.rs b/src/widget.rs index d27e4c72..c619bcfa 100644 --- a/src/widget.rs +++ b/src/widget.rs @@ -39,7 +39,6 @@ pub mod image { pub use crate::runtime::image::Handle; pub use crate::runtime::widget::image::viewer; pub use crate::runtime::widget::image::{Image, Viewer}; - pub use crate::runtime::ContentFit; } #[cfg_attr(docsrs, doc(cfg(feature = "svg")))] -- cgit From 83c0e0f7a862ddcefedfb4ef11a11f9bd5245605 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 16 Feb 2022 17:59:39 +0700 Subject: Add `ContentFit` support to `Svg` widget --- native/src/widget/image.rs | 1 - native/src/widget/svg.rs | 83 +++++++++++++++++++++++++++++++++++++--------- 2 files changed, 67 insertions(+), 17 deletions(-) diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index a2e7f765..8ccc7856 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -120,7 +120,6 @@ where _cursor_position: Point, _viewport: &Rectangle, ) { - // The raw w/h of the underlying image let (width, height) = renderer.dimensions(&self.handle); let image_size = Size::new(width as f32, height as f32); diff --git a/native/src/widget/svg.rs b/native/src/widget/svg.rs index f212dfcb..9e3639db 100644 --- a/native/src/widget/svg.rs +++ b/native/src/widget/svg.rs @@ -2,7 +2,10 @@ use crate::layout; use crate::renderer; use crate::svg::{self, Handle}; -use crate::{Element, Hasher, Layout, Length, Point, Rectangle, Size, Widget}; +use crate::{ + ContentFit, Element, Hasher, Layout, Length, Point, Rectangle, Size, + Vector, Widget, +}; use std::hash::Hash; use std::path::PathBuf; @@ -18,6 +21,7 @@ pub struct Svg { handle: Handle, width: Length, height: Length, + content_fit: ContentFit, } impl Svg { @@ -27,6 +31,7 @@ impl Svg { handle: handle.into(), width: Length::Fill, height: Length::Shrink, + content_fit: ContentFit::Contain, } } @@ -47,6 +52,16 @@ impl Svg { self.height = height; self } + + /// Sets the [`ContentFit`] of the [`Svg`]. + /// + /// Defaults to [`ContentFit::Contain`] + pub fn content_fit(self, content_fit: ContentFit) -> Self { + Self { + content_fit, + ..self + } + } } impl Widget for Svg @@ -66,24 +81,32 @@ where renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { + // The raw w/h of the underlying image let (width, height) = renderer.dimensions(&self.handle); + let image_size = Size::new(width as f32, height as f32); - let aspect_ratio = width as f32 / height as f32; - - let mut size = limits + // The size to be available to the widget prior to `Shrink`ing + let raw_size = limits .width(self.width) .height(self.height) - .resolve(Size::new(width as f32, height as f32)); - - let viewport_aspect_ratio = size.width / size.height; - - if viewport_aspect_ratio > aspect_ratio { - size.width = width as f32 * size.height / height as f32; - } else { - size.height = height as f32 * size.width / width as f32; - } - - layout::Node::new(size) + .resolve(image_size); + + // The uncropped size of the image when fit to the bounds above + let full_size = self.content_fit.fit(image_size, raw_size); + + // Shrink the widget to fit the resized image, if requested + let final_size = Size { + width: match self.width { + Length::Shrink => f32::min(raw_size.width, full_size.width), + _ => raw_size.width, + }, + height: match self.height { + Length::Shrink => f32::min(raw_size.height, full_size.height), + _ => raw_size.height, + }, + }; + + layout::Node::new(final_size) } fn draw( @@ -94,7 +117,35 @@ where _cursor_position: Point, _viewport: &Rectangle, ) { - renderer.draw(self.handle.clone(), layout.bounds()) + let (width, height) = renderer.dimensions(&self.handle); + let image_size = Size::new(width as f32, height as f32); + + let adjusted_fit = + self.content_fit.fit(image_size, layout.bounds().size()); + let bounds = layout.bounds(); + + let render = |renderer: &mut Renderer| { + let offset = Vector::new( + (bounds.width - adjusted_fit.width).max(0.0) / 2.0, + (bounds.height - adjusted_fit.height).max(0.0) / 2.0, + ); + + let bounds = Rectangle { + width: adjusted_fit.width, + height: adjusted_fit.height, + ..layout.bounds() + }; + + renderer.draw(self.handle.clone(), bounds + offset) + }; + + if adjusted_fit.width > bounds.width + || adjusted_fit.height > bounds.height + { + renderer.with_layer(layout.bounds(), render); + } else { + render(renderer) + } } fn hash_layout(&self, state: &mut Hasher) { -- cgit From 8d94cd4c5c9e33965c24e59fd4710218e346be24 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 16 Feb 2022 18:09:22 +0700 Subject: Remove redundant `layout.bounds()` calls in `Image` and `Svg` --- native/src/widget/image.rs | 11 +++++------ native/src/widget/svg.rs | 11 +++++------ 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index 8ccc7856..6aab76e4 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -123,9 +123,8 @@ where let (width, height) = renderer.dimensions(&self.handle); let image_size = Size::new(width as f32, height as f32); - let adjusted_fit = - self.content_fit.fit(image_size, layout.bounds().size()); let bounds = layout.bounds(); + let adjusted_fit = self.content_fit.fit(image_size, bounds.size()); let render = |renderer: &mut Renderer| { let offset = Vector::new( @@ -133,19 +132,19 @@ where (bounds.height - adjusted_fit.height).max(0.0) / 2.0, ); - let bounds = Rectangle { + let drawing_bounds = Rectangle { width: adjusted_fit.width, height: adjusted_fit.height, - ..layout.bounds() + ..bounds }; - renderer.draw(self.handle.clone(), bounds + offset) + renderer.draw(self.handle.clone(), drawing_bounds + offset) }; if adjusted_fit.width > bounds.width || adjusted_fit.height > bounds.height { - renderer.with_layer(layout.bounds(), render); + renderer.with_layer(bounds, render); } else { render(renderer) } diff --git a/native/src/widget/svg.rs b/native/src/widget/svg.rs index 9e3639db..5ce8d25b 100644 --- a/native/src/widget/svg.rs +++ b/native/src/widget/svg.rs @@ -120,9 +120,8 @@ where let (width, height) = renderer.dimensions(&self.handle); let image_size = Size::new(width as f32, height as f32); - let adjusted_fit = - self.content_fit.fit(image_size, layout.bounds().size()); let bounds = layout.bounds(); + let adjusted_fit = self.content_fit.fit(image_size, bounds.size()); let render = |renderer: &mut Renderer| { let offset = Vector::new( @@ -130,19 +129,19 @@ where (bounds.height - adjusted_fit.height).max(0.0) / 2.0, ); - let bounds = Rectangle { + let drawing_bounds = Rectangle { width: adjusted_fit.width, height: adjusted_fit.height, - ..layout.bounds() + ..bounds }; - renderer.draw(self.handle.clone(), bounds + offset) + renderer.draw(self.handle.clone(), drawing_bounds + offset) }; if adjusted_fit.width > bounds.width || adjusted_fit.height > bounds.height { - renderer.with_layer(layout.bounds(), render); + renderer.with_layer(bounds, render); } else { render(renderer) } -- cgit From 15b4bbd49dfb4f70e1e73699958a764c0568b452 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 16 Feb 2022 18:16:09 +0700 Subject: Hash `content_fit` in `hash_layout` of `Image` and `Svg` --- native/src/widget/image.rs | 1 + native/src/widget/svg.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/native/src/widget/image.rs b/native/src/widget/image.rs index 6aab76e4..83c24ee5 100644 --- a/native/src/widget/image.rs +++ b/native/src/widget/image.rs @@ -157,6 +157,7 @@ where self.handle.hash(state); self.width.hash(state); self.height.hash(state); + self.content_fit.hash(state); } } diff --git a/native/src/widget/svg.rs b/native/src/widget/svg.rs index 5ce8d25b..22aac331 100644 --- a/native/src/widget/svg.rs +++ b/native/src/widget/svg.rs @@ -153,6 +153,7 @@ where self.handle.hash(state); self.width.hash(state); self.height.hash(state); + self.content_fit.hash(state); } } -- cgit From 6f6ce15a2055ddbc15dbe71bc811dbe1c8f42068 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 16 Feb 2022 18:16:22 +0700 Subject: Keep using Ferris in the image section of the `tour` Wide ferris is cute :3 --- examples/tour/src/main.rs | 33 +++++++-------------------------- 1 file changed, 7 insertions(+), 26 deletions(-) diff --git a/examples/tour/src/main.rs b/examples/tour/src/main.rs index 9a675168..a4863724 100644 --- a/examples/tour/src/main.rs +++ b/examples/tour/src/main.rs @@ -612,7 +612,7 @@ impl<'a> Step { Self::container("Image") .push(Text::new("Pictures of things in all shapes and sizes!")) - .push(logo(height, current_fit)) + .push(ferris(height, current_fit)) .push(Slider::new( slider, 50..=500, @@ -647,7 +647,7 @@ impl<'a> Step { .horizontal_alignment(alignment::Horizontal::Center), ) .push(Column::new().height(Length::Units(4096))) - .push(ferris(200)) + .push(ferris(200, ContentFit::Contain)) .push( Text::new("You made it!") .width(Length::Fill) @@ -733,8 +733,10 @@ impl<'a> Step { } } -/// Passing fit=None defaults to ContentFit::Contain -fn ferris<'a>(width: u16) -> Container<'a, StepMessage> { +fn ferris<'a>( + height: u16, + content_fit: ContentFit, +) -> Container<'a, StepMessage> { Container::new( // This should go away once we unify resource loading on native // platforms @@ -746,29 +748,8 @@ fn ferris<'a>(width: u16) -> Container<'a, StepMessage> { env!("CARGO_MANIFEST_DIR"), )) } - .width(Length::Units(width)) - .content_fit(ContentFit::Contain), - ) - .width(Length::Fill) - .center_x() -} - -/// Passing fit=None defaults to ContentFit::Contain -fn logo<'a>(height: u16, fit: ContentFit) -> Container<'a, StepMessage> { - Container::new( - // This should go away once we unify resource loading on native - // platforms - if cfg!(target_arch = "wasm32") { - Image::new("tour/images/logo.png") - } else { - Image::new(format!( - "{}/images/logo.png", - env!("CARGO_MANIFEST_DIR"), - )) - } - .width(Length::Fill) .height(Length::Units(height)) - .content_fit(fit), + .content_fit(content_fit), ) .width(Length::Fill) .center_x() -- cgit From 33b9b50883dfcc9838f7792d884324aaffef0a41 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 23 Feb 2022 16:32:12 +0700 Subject: Showcase only `Contain`, `Cover`, and `Fill` image modes in `tour` --- examples/tour/src/main.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/tour/src/main.rs b/examples/tour/src/main.rs index a4863724..e199c88c 100644 --- a/examples/tour/src/main.rs +++ b/examples/tour/src/main.rs @@ -590,12 +590,10 @@ impl<'a> Step { slider: &'a mut slider::State, current_fit: ContentFit, ) -> Column<'a, StepMessage> { - const FIT_MODES: [(ContentFit, &str); 5] = [ + const FIT_MODES: [(ContentFit, &str); 3] = [ (ContentFit::Contain, "Contain"), (ContentFit::Cover, "Cover"), (ContentFit::Fill, "Fill"), - (ContentFit::None, "None"), - (ContentFit::ScaleDown, "Only Scale Down"), ]; let mode_selector = FIT_MODES.iter().fold( @@ -624,6 +622,7 @@ impl<'a> Step { .width(Length::Fill) .horizontal_alignment(alignment::Horizontal::Center), ) + .push(Text::new("Pick a content fit strategy:")) .push(mode_selector) } @@ -821,7 +820,8 @@ pub enum Layout { } mod style { - use iced::{button, Background, Color, Vector}; + use iced::button; + use iced::{Background, Color, Vector}; pub enum Button { Primary, -- cgit