diff --git a/core/src/size.rs b/core/src/size.rs index baa80b01..70eb38fe 100644 --- a/core/src/size.rs +++ b/core/src/size.rs @@ -52,7 +52,7 @@ impl Size { } } - /// Rotates the given [`Size`] and returns the minimum [`Size`] + /// Rotates this [`Size`] and returns the minimum [`Size`] /// containing it. pub fn rotate(self, rotation: Radians) -> Size { let radians = f32::from(rotation); @@ -64,6 +64,15 @@ impl Size { + (self.height * radians.cos()).abs(), } } + + /// Applies an aspect ratio to this [`Size`] without + /// exceeding its bounds. + pub const fn ratio(self, aspect_ratio: f32) -> Size { + Size { + width: (self.height * aspect_ratio).min(self.width), + height: (self.width / aspect_ratio).min(self.height), + } + } } impl Size { diff --git a/examples/layout/Cargo.toml b/examples/layout/Cargo.toml index 22fd7218..9f66bae9 100644 --- a/examples/layout/Cargo.toml +++ b/examples/layout/Cargo.toml @@ -6,4 +6,4 @@ edition = "2024" publish = false [dependencies] -iced = { path = "../..", features = ["canvas"] } +iced = { path = "../..", features = ["canvas", "debug"] } diff --git a/examples/layout/src/main.rs b/examples/layout/src/main.rs index c4faf319..b21f2094 100644 --- a/examples/layout/src/main.rs +++ b/examples/layout/src/main.rs @@ -3,7 +3,7 @@ use iced::keyboard; use iced::mouse; use iced::widget::{ button, canvas, center, center_y, checkbox, column, container, pick_list, - pin, row, rule, scrollable, space, stack, text, + pin, responsive, row, rule, scrollable, space, stack, text, }; use iced::{ Center, Element, Fill, Font, Length, Point, Rectangle, Renderer, Shrink, @@ -153,6 +153,10 @@ impl Example { title: "Pinning", view: pinning, }, + Self { + title: "Responsive", + view: responsive_, + }, ]; fn is_first(self) -> bool { @@ -333,6 +337,42 @@ fn pinning<'a>() -> Element<'a, Message> { .into() } +fn responsive_<'a>() -> Element<'a, Message> { + column![ + responsive(|size| { + container(center( + text!("{}x{}px", size.width, size.width).font(Font::MONOSPACE), + )) + .clip(true) + .width(size.width / 4.0) + .height(size.width / 4.0) + .style(container::bordered_box) + .into() + }) + .width(Shrink) + .height(Shrink), + responsive(|size| { + let size = size.ratio(16.0 / 9.0); + + container(center( + text!("{:.0}x{:.0}px (16:9)", size.width, size.height) + .font(Font::MONOSPACE), + )) + .clip(true) + .width(size.width) + .height(size.height) + .style(container::bordered_box) + .into() + }) + .width(Shrink) + .height(Shrink) + ] + .align_x(Center) + .spacing(10) + .padding(10) + .into() +} + fn square<'a>(size: impl Into + Copy) -> Element<'a, Message> { struct Square;