quad_guage/src/main.rs
2024-10-21 14:44:55 -06:00

66 lines
2.1 KiB
Rust

use macroquad::{prelude::*, ui::root_ui};
#[macroquad::main("BasicShapes")]
async fn main() {
let mut percent = 0.;
loop {
clear_background(BLACK);
root_ui().group(0, vec2(100., 100.), |ui| {
ui.slider(1, "Slider", 0.0..100.0, &mut percent);
});
let ((x1,y1),(x2,y2)) = gauge(screen_width()/2., screen_height()/2., percent/100.0, &format!("{:.1}%", percent));
draw_rectangle_lines(x1, y1, x2-x1, y2-y1, 2., PURPLE);
next_frame().await
}
}
/// # Parameters
/// `percent` is percent of the gauge to be filled. `text` supports 6 chars nicely.
/// # Return
/// `((x1,y1),(x2,y2))` Returns the upper-right and lower-left coordinates. Useful for spacing this item next to others.
/// You could visualize this with a bounding box:
/// ```
/// let ((x1,y1),(x2,y2)) = gauge(screen_width()/2., screen_height()/2., 0.6, &format!("60%"));
/// draw_rectangle_lines(x1, y1, x2-x1, y2-y1, 2., PURPLE);
/// ```
fn gauge(x: f32, y: f32, percent: f32, text: &str) -> ((f32, f32), (f32, f32)) {
let scale = 2.;
let radius = 20.*scale;
let thickness = 20.*scale;
let yellow_threshold = 0.6;
let red_threshold= 0.8;
let color = if percent < yellow_threshold {
GREEN
} else if percent < red_threshold {
YELLOW
} else {
RED
};
// Outline
draw_circle(x, y, (radius + thickness) * 1.1, LIGHTGRAY);
// Background
draw_circle(x, y, radius + thickness, WHITE);
// Value background
draw_arc(x, y, 100, radius, 180., thickness, 180., GRAY);
// Value Forground
draw_arc(x, y, 100, radius, 180., thickness, 180.*percent, color);
// Show value
let params = TextParams { color: BLACK, font_size: 25*scale as u16,..Default::default()} ;
let measurement = measure_text(text, None, params.font_size, params.font_scale);
let x_offset = measurement.width / 2.;
let y_offset = measurement.height*1.5;
draw_text_ex(text, x-x_offset, y+y_offset, params);
// Get upper-left and lower-right coordinates
let total_radius = (radius+thickness)*1.1;
((x-total_radius,y-total_radius), (x+total_radius,y+total_radius))
}