ZIm/crates/gpui/examples/image.rs
Bennet Bo Fenner dd74643993
gpui: Support loading image from filesystem (#6978)
This PR implements support for loading and displaying images from a
local file using gpui's `img` element.

API Changes:
- Changed `SharedUrl` to `SharedUrl::File`, `SharedUrl::Network`

Usage:
```rust
// load from network
img(SharedUrl::network(...)) // previously img(SharedUrl(...)

// load from filesystem
img(SharedUrl::file(...))
```

This will be useful when implementing markdown image support, because we
need to be able to render images from the filesystem (relative/absolute
path), e.g. when implementing markdown preview #5064.

I also added an example `image` to the gpui crate, let me know if this
is useful. Showcase:
<img width="872" alt="image"
src="https://github.com/zed-industries/zed/assets/53836821/b4310a26-db81-44fa-9a7b-61e7d0ad4349">

**Note**: The example is fetching images from [Lorem
Picsum](https://picsum.photos) ([Github
Repo](https://github.com/DMarby/picsum-photos)), which is a free
resource for fetching images in a specific size. Please let me know if
you're okay with using this in the example.
2024-01-29 21:56:51 -08:00

59 lines
1.6 KiB
Rust

use gpui::*;
#[derive(IntoElement)]
struct ImageFromResource {
text: SharedString,
resource: SharedUrl,
}
impl RenderOnce for ImageFromResource {
fn render(self, _: &mut WindowContext) -> impl IntoElement {
div().child(
div()
.flex_row()
.size_full()
.gap_4()
.child(self.text)
.child(img(self.resource).w(px(512.0)).h(px(512.0))),
)
}
}
struct ImageShowcase {
local_resource: SharedUrl,
remote_resource: SharedUrl,
}
impl Render for ImageShowcase {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
div()
.flex()
.flex_row()
.size_full()
.justify_center()
.items_center()
.gap_8()
.bg(rgb(0xFFFFFF))
.child(ImageFromResource {
text: "Image loaded from a local file".into(),
resource: self.local_resource.clone(),
})
.child(ImageFromResource {
text: "Image loaded from a remote resource".into(),
resource: self.remote_resource.clone(),
})
}
}
fn main() {
env_logger::init();
App::new().run(|cx: &mut AppContext| {
cx.open_window(WindowOptions::default(), |cx| {
cx.new_view(|_cx| ImageShowcase {
local_resource: SharedUrl::file("../zed/resources/app-icon.png"),
remote_resource: SharedUrl::network("https://picsum.photos/512/512"),
})
});
});
}