Last active
April 2, 2025 01:38
-
-
Save ggand0/3e5c57ce16d713e5bf32c3be8f8f4df0 to your computer and use it in GitHub Desktop.
The first commit in my image viewer project with Iced 0.10.0 (snippet for blog post)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use iced::{ | |
| button, Button, Column, Element, Image, Length, Row, Sandbox, Settings, Text, | |
| Container | |
| }; | |
| use iced::alignment::{Horizontal, Vertical}; | |
| // Define the application state | |
| #[derive(Default)] | |
| struct ImageViewer { | |
| image_path: String, | |
| load_button_state: button::State, | |
| } | |
| // Define application messages | |
| #[derive(Debug, Clone)] | |
| enum Message { | |
| LoadImage, | |
| } | |
| impl Sandbox for ImageViewer { | |
| type Message = Message; | |
| fn new() -> Self { | |
| ImageViewer::default() | |
| } | |
| fn title(&self) -> String { | |
| String::from("Image Viewer") | |
| } | |
| fn update(&mut self, message: Message) { | |
| match message { | |
| Message::LoadImage => { | |
| self.image_path = "sample.jpg".to_string(); | |
| } | |
| } | |
| } | |
| fn view(&mut self) -> Element<Message> { | |
| let image: Element<Message> = if self.image_path.is_empty() { | |
| Text::new("No image loaded") | |
| .size(30) | |
| .width(Length::Fill) | |
| .height(Length::Fill) | |
| .horizontal_alignment(Horizontal::Center) | |
| .vertical_alignment(Vertical::Center) | |
| .into() | |
| } else { | |
| Image::new(&self.image_path) | |
| .width(Length::Fill) | |
| .height(Length::Fill) | |
| .into() | |
| }; | |
| let load_button: Element<Message> = Button::new(&mut self.load_button_state, Text::new("Load Image")) | |
| .on_press(Message::LoadImage) | |
| .into(); | |
| // Create a simple UI layout with a button and the image | |
| let content: Element<Message> = Column::new() | |
| .push(load_button) | |
| .push(Row::new().push(image).spacing(10)) | |
| .spacing(20) | |
| .padding(20) | |
| .into(); | |
| // Wrap the content in a container | |
| Container::new(content) | |
| .width(Length::Fill) | |
| .height(Length::Fill) | |
| .center_x() | |
| .center_y() | |
| .into() | |
| } | |
| } | |
| fn main() -> iced::Result { | |
| ImageViewer::run(Settings::default()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment