Skip to content

Commit

Permalink
Add ImageFit for Image component, defaulting to Fit so that images do…
Browse files Browse the repository at this point in the history
…n't stretch
  • Loading branch information
LPGhatguy committed Jan 24, 2025
1 parent 3131f4d commit 1057cbb
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
37 changes: 35 additions & 2 deletions crates/yakui-widgets/src/widgets/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ pub struct Image {
pub image: Option<TextureId>,
pub size: Vec2,
pub color: Color,
pub fit_mode: ImageFit,
}

#[derive(Debug, Clone, Copy)]
pub enum ImageFit {
Stretch,
Fit,
}

impl Image {
Expand All @@ -27,6 +34,7 @@ impl Image {
image: Some(image.into()),
size,
color: Color::WHITE,
fit_mode: ImageFit::Fit,
}
}

Expand All @@ -52,6 +60,7 @@ impl Widget for ImageWidget {
image: None,
size: Vec2::ZERO,
color: Color::WHITE,
fit_mode: ImageFit::Stretch,
},
}
}
Expand All @@ -60,8 +69,32 @@ impl Widget for ImageWidget {
self.props = props;
}

fn layout(&self, _ctx: LayoutContext<'_>, input: Constraints) -> Vec2 {
input.constrain_min(self.props.size)
fn layout(&self, ctx: LayoutContext<'_>, input: Constraints) -> Vec2 {
let mut output_size = input.constrain(self.props.size);

match self.props.fit_mode {
ImageFit::Stretch => {}

ImageFit::Fit => {
if let Some(TextureId::Managed(id)) = self.props.image {
if let Some(texture) = ctx.paint.texture(id) {
let real_size = texture.size().as_vec2();
let aspect_ratio = real_size.x / real_size.y;

let width_from_height = output_size.y * aspect_ratio;
let height_from_width = output_size.x / aspect_ratio;

if output_size.x < width_from_height {
output_size = Vec2::new(output_size.x, height_from_width);
} else {
output_size = Vec2::new(width_from_height, output_size.y);
}
}
}
}
}

output_size
}

fn paint(&self, ctx: PaintContext<'_>) {
Expand Down
5 changes: 4 additions & 1 deletion crates/yakui/examples/images.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use yakui::center;
use yakui::{image, nineslice, pad, widgets::Pad, Vec2};

use bootstrap::ExampleState;

pub fn run(state: &mut ExampleState) {
pad(Pad::all(20.0), || {
nineslice(state.brown_inlay, Pad::all(15.0), 9.0, || {
image(state.monkey, Vec2::new(400.0, 400.0));
center(|| {
image(state.monkey, Vec2::splat(800.0));
});
});
});
}
Expand Down

0 comments on commit 1057cbb

Please sign in to comment.