Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor image draw to standalone function #1682

Merged
merged 1 commit into from
Jan 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 40 additions & 28 deletions native/src/widget/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,45 @@ where
layout::Node::new(final_size)
}

/// Draws an [`Image`]
pub fn draw<Renderer, Handle>(
renderer: &mut Renderer,
layout: Layout<'_>,
handle: &Handle,
content_fit: ContentFit,
) where
Renderer: image::Renderer<Handle = Handle>,
Handle: Clone + Hash,
{
let Size { width, height } = renderer.dimensions(handle);
let image_size = Size::new(width as f32, height as f32);

let bounds = layout.bounds();
let adjusted_fit = content_fit.fit(image_size, bounds.size());

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 drawing_bounds = Rectangle {
width: adjusted_fit.width,
height: adjusted_fit.height,
..bounds
};

renderer.draw(handle.clone(), drawing_bounds + offset)
};

if adjusted_fit.width > bounds.width || adjusted_fit.height > bounds.height
{
renderer.with_layer(bounds, render);
} else {
render(renderer)
}
}

impl<Message, Renderer, Handle> Widget<Message, Renderer> for Image<Handle>
where
Renderer: image::Renderer<Handle = Handle>,
Expand Down Expand Up @@ -149,34 +188,7 @@ where
_cursor_position: Point,
_viewport: &Rectangle,
) {
let Size { width, height } = renderer.dimensions(&self.handle);
let image_size = Size::new(width as f32, height as f32);

let bounds = layout.bounds();
let adjusted_fit = self.content_fit.fit(image_size, bounds.size());

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 drawing_bounds = Rectangle {
width: adjusted_fit.width,
height: adjusted_fit.height,
..bounds
};

renderer.draw(self.handle.clone(), drawing_bounds + offset)
};

if adjusted_fit.width > bounds.width
|| adjusted_fit.height > bounds.height
{
renderer.with_layer(bounds, render);
} else {
render(renderer)
}
draw(renderer, layout, &self.handle, self.content_fit)
}
}

Expand Down