Add support for ContentFit for Image

This commit is contained in:
Emi Simpson 2022-01-22 20:09:35 -05:00 committed by Héctor Ramón Jiménez
parent adce9e0421
commit ca1fcdaf14
No known key found for this signature in database
GPG key ID: 140CC052C94F138E
6 changed files with 249 additions and 35 deletions

119
core/src/image.rs Normal file
View file

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

View file

@ -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;

View file

@ -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)),
.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::Fill)
.height(Length::Units(height))
.fit(fit),
)
.width(Length::Fill)
.center_x()

View file

@ -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};

View file

@ -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: Handle,
width: Length,
height: Length,
fit: ContentFit,
}
impl<Handle> Image<Handle> {
@ -35,6 +38,7 @@ impl<Handle> Image<Handle> {
handle: handle.into(),
width: Length::Shrink,
height: Length::Shrink,
fit: ContentFit::Contain,
}
}
@ -49,6 +53,13 @@ impl<Handle> Image<Handle> {
self.height = height;
self
}
/// Sets the image fit
///
/// Defaults to [`ContentFit::Contain`]
pub fn fit(self, fit: ContentFit) -> Self {
Self { fit, ..self }
}
}
impl<Message, Renderer, Handle> Widget<Message, Renderer> for Image<Handle>
@ -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));
.resolve(image_size);
let viewport_aspect_ratio = size.width / size.height;
// The uncropped size of the image when fit to the bounds above
let full_size = self.fit.fit(image_size, raw_size);
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;
}
// 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(size)
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) {

View file

@ -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")))]