summaryrefslogtreecommitdiffstats
path: root/examples/tour/renderer/slider.rs
blob: 146cee184b186a00a816b36f6839ae9a84246fa8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use super::Renderer;

use ggez::graphics::{DrawParam, Rect};
use iced::{slider, MouseCursor, Point, Rectangle};
use std::ops::RangeInclusive;

const RAIL: Rect = Rect {
    x: 98.0,
    y: 56.0,
    w: 1.0,
    h: 4.0,
};

const MARKER: Rect = Rect {
    x: RAIL.x + 28.0,
    y: RAIL.y,
    w: 16.0,
    h: 24.0,
};

impl slider::Renderer for Renderer<'_> {
    fn draw(
        &mut self,
        cursor_position: Point,
        bounds: Rectangle,
        state: &slider::State,
        range: RangeInclusive<f32>,
        value: f32,
    ) -> MouseCursor {
        let width = self.spritesheet.width() as f32;
        let height = self.spritesheet.height() as f32;

        self.sprites.add(DrawParam {
            src: Rect {
                x: RAIL.x / width,
                y: RAIL.y / height,
                w: RAIL.w / width,
                h: RAIL.h / height,
            },
            dest: ggez::mint::Point2 {
                x: bounds.x + MARKER.w as f32 / 2.0,
                y: bounds.y + 12.5,
            },
            scale: ggez::mint::Vector2 {
                x: bounds.width - MARKER.w as f32,
                y: 1.0,
            },
            ..DrawParam::default()
        });

        let (range_start, range_end) = range.into_inner();

        let marker_offset = (bounds.width - MARKER.w as f32)
            * ((value - range_start) / (range_end - range_start).max(1.0));

        let mouse_over = bounds.contains(cursor_position);
        let is_active = state.is_dragging() || mouse_over;

        self.sprites.add(DrawParam {
            src: Rect {
                x: (MARKER.x + (if is_active { MARKER.w } else { 0.0 }))
                    / width,
                y: MARKER.y / height,
                w: MARKER.w / width,
                h: MARKER.h / height,
            },
            dest: ggez::mint::Point2 {
                x: bounds.x + marker_offset.round(),
                y: bounds.y + (if state.is_dragging() { 2.0 } else { 0.0 }),
            },
            ..DrawParam::default()
        });

        if state.is_dragging() {
            MouseCursor::Grabbing
        } else if mouse_over {
            MouseCursor::Grab
        } else {
            MouseCursor::OutOfBounds
        }
    }
}