macroquad/ui/widgets/
texture.rs

1use crate::{
2    math::{Rect, Vec2},
3    texture::Texture2D,
4    ui::{Layout, Ui},
5};
6
7pub struct Texture {
8    position: Option<Vec2>,
9    w: f32,
10    h: f32,
11    texture: Texture2D,
12}
13
14impl Texture {
15    pub const fn new(texture: Texture2D) -> Texture {
16        Texture {
17            position: None,
18            w: 100.,
19            h: 100.,
20            texture,
21        }
22    }
23
24    pub fn size(self, w: f32, h: f32) -> Self {
25        Texture { w, h, ..self }
26    }
27
28    pub fn position<P: Into<Option<Vec2>>>(self, position: P) -> Self {
29        let position = position.into();
30
31        Texture { position, ..self }
32    }
33
34    pub fn ui(self, ui: &mut Ui) -> bool {
35        let context = ui.get_active_window_context();
36
37        let size = Vec2::new(self.w, self.h);
38
39        let pos = context
40            .window
41            .cursor
42            .fit(size, self.position.map_or(Layout::Vertical, Layout::Free));
43        context
44            .window
45            .painter
46            .draw_raw_texture(Rect::new(pos.x, pos.y, self.w, self.h), &self.texture);
47
48        let rect = Rect::new(pos.x, pos.y, size.x, size.y);
49        let hovered = rect.contains(context.input.mouse_position);
50
51        context.focused && hovered && context.input.click_up
52    }
53}
54
55impl Ui {
56    pub fn texture(&mut self, texture: Texture2D, w: f32, h: f32) -> bool {
57        Texture::new(texture).size(w, h).ui(self)
58    }
59}