Skip to content
Snippets Groups Projects
image.rs 1.98 KiB
Newer Older
Finn Bear's avatar
Finn Bear committed
use crate::color::{set_alpha, set_style_alpha};
use crate::egui::{Color32, TextureHandle, Ui};
use eframe::egui;
use eframe::egui::style::Margin;
use eframe::egui::{Frame, Pos2, Vec2, Widget, Window};

/// A bitmap image i.e. an example of generative art.
pub struct Image {
    /// How many pixels of height the images should occupy.
    pub height: f32,
    /// How opaque the image is.
    pub alpha: f32,
    /// Center position.
    pub position: Option<Pos2>,
}

impl Default for Image {
    fn default() -> Self {
        Self::new(128.0, 1.0, None)
    }
}

impl Image {
    pub fn new(height: f32, alpha: f32, position: Option<Pos2>) -> Self {
        Self {
            height,
            alpha,
            position,
        }
    }

    /// Change the height of the image.
    pub fn height(mut self, height: f32) -> Self {
        self.height = height;
        self
    }

    /// Change the alpha of the image.
    pub fn alpha(mut self, alpha: f32) -> Self {
        self.alpha = alpha;
        self
    }

    /// Change the position of the image.
    pub fn position(mut self, position: Pos2) -> Self {
        // We assume that, if you call this method, you don't want [`None`].
        self.position = Some(position);
        self
    }

    pub fn show(&mut self, ui: &mut Ui, texture: &TextureHandle) {
Finn Bear's avatar
Finn Bear committed
        let mut window = Window::new(format!("{}-{}", texture.name(), self.height))
Finn Bear's avatar
Finn Bear committed
            .title_bar(false)
            .resizable(false)
            // Reduce margin of images.
            .frame(
                Frame::window(&set_style_alpha(ui.style(), self.alpha)).margin(Margin::same(5.0)),
            );

        if let Some(position) = self.position {
            window = window.default_pos(position).fixed_pos(position);
        }

        window.show(ui.ctx(), |ui| {
            // TODO: Support non-square images.
            egui::Image::new(texture, Vec2::splat(self.height))
                .tint(set_alpha(Color32::WHITE, self.alpha))
                .ui(ui);
        });
    }
}