raylib_ext/
lib.rs

1use raylib::prelude::*;
2
3/// Trait for drawing text with different alignments (centered or right-aligned)
4pub trait TextAlignment {
5  #[allow(dead_code)] fn draw_centered_text(&mut self, text: &str, x: i32, y: i32, font_size: i32, color: impl Into<ffi::Color>) -> ();
6  #[allow(dead_code)] fn draw_right_aligned_text(&mut self, text: &str, x: i32, y: i32, font_size: i32, color: impl Into<ffi::Color>) -> ();
7  #[allow(dead_code)] fn measure_text_ext(&mut self, text: &str, font_size: i32) -> (i32, i32);
8}
9
10/// Implement the `TextAlignment` trait for `RaylibDrawHandle` to enable custom text drawing
11impl TextAlignment for RaylibDrawHandle<'_> {
12  /// Draw text centered at the specified (x, y) position
13  ///
14  /// # Example:
15  /// ```rust
16  /// use raylib::prelude::*;
17  /// use raylib_ext::*;
18  ///
19  /// fn main() {
20  ///   let (mut rl, thread) = init()
21  ///     .size(640, 480)
22  ///     .title("Hello, World")
23  ///     .build();
24  ///
25  ///   while !rl.window_should_close() {
26  ///     let mut d = rl.begin_drawing(&thread);
27  ///
28  ///     d.clear_background(Color::WHITE);
29  ///
30  ///     // Draws text where (x, y) is in the middle of the text instead of top-left
31  ///     d.draw_centered_text("Hello, world!", 12, 12, 20, Color::BLACK);
32  ///   }
33  /// }
34  /// ```
35  #[allow(dead_code)]
36  fn draw_centered_text(&mut self, text: &str, x: i32, y: i32, font_size: i32, color: impl Into<ffi::Color>) -> () {
37    let text_width = self.measure_text(text, font_size);
38    let final_x = x - (text_width / 2);  // Center horizontally
39    let final_y = y - (font_size / 2);   // Center vertically (based on font size)
40    self.draw_text(text, final_x, final_y, font_size, color);
41  }
42
43  /// Draw text right-aligned at the specified (x, y) position
44  ///
45  /// # Example:
46  /// ```rust
47  /// use raylib::prelude::*;
48  /// use raylib_ext::*;
49  ///
50  /// fn main() {
51  ///   let (mut rl, thread) = init()
52  ///     .size(640, 480)
53  ///     .title("Hello, World")
54  ///     .build();
55  ///
56  ///   while !rl.window_should_close() {
57  ///     let mut d = rl.begin_drawing(&thread);
58  ///
59  ///     d.clear_background(Color::WHITE);
60  ///
61  ///     // Draws text where (x, y) is in the top-right corner instead of top-left
62  ///     d.draw_right_aligned_text("Hello, world!", 12, 12, 20, Color::BLACK);
63  ///   }
64  /// }
65  /// ```
66  #[allow(dead_code)]
67  fn draw_right_aligned_text(&mut self, text: &str, x: i32, y: i32, font_size: i32, color: impl Into<ffi::Color>) -> () {
68    let text_width = self.measure_text(text, font_size);
69    let final_x = x - text_width;  // Align text to the right
70    self.draw_text(text, final_x, y, font_size, color);
71  }
72
73  fn measure_text_ext(&mut self, text: &str, font_size: i32) -> (i32, i32) {
74    (self.measure_text(text, font_size), font_size)
75  }
76}