iced-yoda/web/src/widget/image.rs

91 lines
2 KiB
Rust
Raw Normal View History

2019-09-20 19:15:31 +02:00
use crate::{Bus, Element, Length, Widget};
2019-09-15 18:53:13 +02:00
use dodrio::bumpalo;
2019-09-14 20:54:50 +02:00
/// A frame that displays an image while keeping aspect ratio.
///
/// # Example
///
/// ```
/// # use iced_web::Image;
///
/// let image = Image::new("resources/ferris.png");
/// ```
#[derive(Debug)]
pub struct Image {
/// The image path
pub path: String,
/// The width of the image
pub width: Length,
/// The height of the image
pub height: Length,
}
impl Image {
/// Creates a new [`Image`] with the given path.
///
/// [`Image`]: struct.Image.html
pub fn new<T: Into<String>>(path: T) -> Self {
Image {
path: path.into(),
width: Length::Shrink,
height: Length::Shrink,
}
}
/// Sets the width of the [`Image`] boundaries.
///
/// [`Image`]: struct.Image.html
pub fn width(mut self, width: Length) -> Self {
self.width = width;
self
}
/// Sets the height of the [`Image`] boundaries.
///
/// [`Image`]: struct.Image.html
pub fn height(mut self, height: Length) -> Self {
self.height = height;
self
}
}
2019-09-14 20:54:50 +02:00
impl<Message> Widget<Message> for Image {
2019-09-15 18:53:13 +02:00
fn node<'b>(
&self,
bump: &'b bumpalo::Bump,
_bus: &Bus<Message>,
) -> dodrio::Node<'b> {
use dodrio::builder::*;
let src = bumpalo::format!(in bump, "{}", self.path);
2019-09-15 18:53:13 +02:00
let mut image = img(bump).attr("src", src.into_bump_str());
2019-09-20 19:15:31 +02:00
match self.width {
Length::Shrink => {}
Length::Fill => {
image = image.attr("width", "100%");
}
Length::Units(px) => {
image = image.attr(
"width",
bumpalo::format!(in bump, "{}px", px).into_bump_str(),
);
}
2019-09-15 18:53:13 +02:00
}
// TODO: Complete styling
2019-09-15 18:53:13 +02:00
image.finish()
}
}
2019-09-14 20:54:50 +02:00
impl<'a, Message> From<Image> for Element<'a, Message> {
fn from(image: Image) -> Element<'a, Message> {
2019-09-14 20:54:50 +02:00
Element::new(image)
}
}