Repository navigation
Expand file tree
/
Copy pathtext_button.rs
More file actions
638 lines (553 loc) · 22.2 KB
/
Copy pathtext_button.rs
File metadata and controls
638 lines (553 loc) · 22.2 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
/*
Made by: Mathew Dusome
Jun 13, 2026
Updated: April 16 2026 by Tristan St-Gelasis to change when button action is triggered
To import you need:
Adds a button object
In your ui.rs file add the following to the end of the file:
pub mod text_button;
Then with the other use commands add:
use crate::ui::text_button::TextButton;
Then add the following to the top of your file:
Then above the loop section to use you would go:
let btn_text = TextButton::new(
100.0,
200.0,
200.0,
60.0,
"Click Me",
BLUE,
GREEN,
30
);
You can customize the text colors with:
btn_text.with_text_color(WHITE); // Sets the normal text color
btn_text.with_hover_text_color(YELLOW); // Sets the text color when hovering
You can also specify a custom font with:
btn_text.with_font(my_font.clone());
Otherwise the default system font will be used.
You can add rounded corners to the button with:
btn_text.with_round(10.0);
Where the value is the corner radius in pixels.
Set vertical text alignment (top, center, bottom)
btn_text.with_vertical_alignment(crate::ui::text_button::VerticalAlign::Bottom);
Options: VerticalAlign::Top, VerticalAlign::Center, VerticalAlign::Bottom
You can add a border to the button with:
btn_text.with_border(RED, 2.0);
Where the first value is the border color and the second is the thickness.
Set text alignment (left, center, right)
btn_text.with_alignment(crate::ui::text_button::TextAlign::Right);
Options: TextAlign::Left, TextAlign::Center, TextAlign::Right
Multi-line support
Use \n in the button text to break lines:
btn_text.set_text("Line 1\nLine 2");
To access the button's position:
let x = btn_text.get_x();
let y = btn_text.get_y();
let position = btn_text.get_position(); // Returns a Vec2 with both x and y
To change the button's position:
btn_text.update_position(150.0, 250.0, None, None);
Where the first two values are x and y positions, and the optional values are for width and height.
To change the button's text:
btn_text.set_text("New Text");
Then in the loop you would use:
if btn_text.click() {
}
Note: For buttons with transparent backgrounds (set normal_color with alpha=0),
only the text area is clickable, not the entire button area.
*/
use macroquad::prelude::*;
// Enum for text alignment within a button
// Enum for vertical text alignment within a button
#[allow(unused)]
pub enum VerticalAlign {
Top,
Center,
Bottom,
}
#[allow(unused)]
pub enum TextAlign {
Left,
Center,
Right,
}
#[cfg(feature = "scale")]
use crate::utils::scale::mouse_position_world as mouse_position;
// Custom struct for ButtonText
pub struct TextButton {
x: f32, // Now private
y: f32, // Now private
pub width: f32,
pub height: f32,
text: String, // Now private
pub enabled: bool,
pub normal_color: Color,
pub hover_color: Color,
off_color: Color,
pub text_color: Color,
pub hover_text_color: Color, // Added hover text color
pub font_size: u16,
pub font: Option<Font>, // Store the font directly since Font is Clone
pub corner_radius: f32, // For rounded corners
pub border: bool, // Whether to draw a border
pub border_color: Color, // Color of the border
pub border_thickness: f32, // Thickness of the border
// Cached values for performance
cached_text_width: f32,
cached_text_position: Vec2,
cached_rect: Rect,
pub visible: bool,
// Text alignment
pub text_align: TextAlign,
// Vertical text alignment
pub vertical_align: VerticalAlign,
}
impl TextButton {
pub fn new(x: f32, y: f32, width: f32, height: f32, text: impl Into<String>, normal_color: Color, hover_color: Color, font_size: u16) -> Self {
let enabled = true;
let off_color = lerp_color(normal_color, GRAY, 0.5);
let text_string = text.into();
let text_color = WHITE; // Default text color
// Pre-calculate and cache values
let cached_text_width = measure_text(&text_string, None, font_size, 1.0).width;
let cached_text_position = Vec2::new(
x + (width / 2.0) - (cached_text_width / 2.0),
y + (height / 2.0),
);
let cached_rect = Rect::new(x, y, width, height);
Self {
x,
y,
width,
height,
text: text_string.to_string(),
enabled,
normal_color,
hover_color,
off_color,
text_color,
hover_text_color: text_color, // Default hover text color to regular text color
font_size,
font: None, // Default to None (use system font)
corner_radius: 0.0, // Default to no rounded corners
border: false, // Default to no border
border_color: BLACK, // Default border color
border_thickness: 1.0, // Default border thickness
cached_text_width,
cached_text_position,
cached_rect,
visible: true,
text_align: TextAlign::Center, // Default to center alignment
vertical_align: VerticalAlign::Center, // Default to center vertical alignment
}
}
/// Set the vertical text alignment for the button
#[allow(unused)]
pub fn with_vertical_alignment(&mut self, align: VerticalAlign) -> &mut Self {
self.vertical_align = align;
// No need to update_text_position, handled in draw logic
self
}
/// Set the text alignment for the button
#[allow(unused)]
pub fn with_alignment(&mut self, align: TextAlign) -> &mut Self {
self.text_align = align;
self.update_text_position();
self
}
/// Update cached text position based on alignment
fn update_text_position(&mut self) {
let x = self.x;
let y = self.y;
let width = self.width;
let height = self.height;
let text_width = self.cached_text_width;
let text_x = match self.text_align {
TextAlign::Left => x + 8.0, // Padding from left
TextAlign::Center => x + (width / 2.0) - (text_width / 2.0),
TextAlign::Right => x + width - text_width - 8.0, // Padding from right
};
let text_y = y + (height / 2.0);
self.cached_text_position = Vec2::new(text_x, text_y);
}
// Method to set custom font - taking Font by value since it implements Clone
#[allow(unused)]
pub fn with_font(&mut self, font: Font) -> &mut Self {
self.font = Some(font.clone());
// Update cached text width with the new font
self.cached_text_width = measure_text(&self.text, Some(&font), self.font_size, 1.0).width;
// Update text position based on new measurement
self.cached_text_position = Vec2::new(
self.x + (self.width / 2.0) - (self.cached_text_width / 2.0),
self.y + (self.height / 2.0),
);
self
}
// Method to set rounded corners
#[allow(unused)]
pub fn with_round(&mut self, radius: f32) -> &mut Self {
self.corner_radius = radius;
self
}
// Method to add border with custom color and thickness
#[allow(unused)]
pub fn with_border(&mut self, color: Color, thickness: f32) -> &mut Self {
self.border = true;
self.border_color = color;
self.border_thickness = thickness;
self
}
// Method to set hover text color
#[allow(unused)]
pub fn with_hover_text_color(&mut self, color: Color) -> &mut Self {
self.hover_text_color = color;
self
}
// Method to set text color
#[allow(unused)]
pub fn with_text_color(&mut self, color: Color) -> &mut Self {
self.text_color = color;
if self.hover_text_color == WHITE { // Only update if it wasn't explicitly set
self.hover_text_color = color;
}
self
}
// Getter for x position
#[allow(unused)]
pub fn get_x(&self) -> f32 {
self.x
}
// Getter for y position
#[allow(unused)]
pub fn get_y(&self) -> f32 {
self.y
}
// Getter for position as Vec2
#[allow(unused)]
pub fn get_position(&self) -> Vec2 {
Vec2::new(self.x, self.y)
}
// Getter for the button text
#[allow(unused)]
pub fn get_text(&self) -> &str {
&self.text
}
// Setter for the button text - updates cached measurements
#[allow(unused)]
pub fn set_text<T: Into<String>>(&mut self, text: T) -> &mut Self {
self.text = text.into();
// Update cached text measurements
self.cached_text_width = match &self.font {
Some(font) => measure_text(&self.text, Some(font), self.font_size, 1.0).width,
None => measure_text(&self.text, None, self.font_size, 1.0).width,
};
self.update_text_position();
self
}
// Update method to recalculate values when position or size changes
#[allow(unused)]
pub fn update_position(&mut self, x: f32, y: f32, width: Option<f32>, height: Option<f32>) -> &mut Self {
self.x = x;
self.y = y;
if let Some(w) = width {
self.width = w;
}
if let Some(h) = height {
self.height = h;
}
// Update cached rectangle
self.cached_rect = Rect::new(self.x, self.y, self.width, self.height);
self.update_text_position();
self
}
pub fn click(&self) -> bool {
if !self.visible {
return false; // If not visible, don't process clicks
}
// Get mouse position
let (mouse_x, mouse_y) = mouse_position();
let mouse_pos = Vec2::new(mouse_x, mouse_y);
// Check if the background is transparent (alpha is 0)
let is_background_transparent = self.normal_color.a == 0.0;
// Determine is_hovered based on background transparency
let is_hovered = if is_background_transparent {
// If transparent, only detect clicks on the text area
let text_height = self.font_size as f32; // Approximate text height
let text_rect = Rect::new(
self.cached_text_position.x,
self.cached_text_position.y - text_height,
self.cached_text_width,
text_height
);
text_rect.contains(mouse_pos)
} else {
// Otherwise use the full button area
self.cached_rect.contains(mouse_pos)
};
// Draw the text button with a bit of depth so it reads as a clickable control.
let is_pressed = is_hovered && self.enabled && is_mouse_button_down(MouseButton::Left);
let mut button_color = if self.enabled {
if is_hovered {
self.hover_color
} else {
self.normal_color
}
} else {
self.off_color
};
// Slightly darken while pressed to mimic a physical button press.
if is_pressed {
button_color = shade_color(button_color, 0.80);
}
let is_background_transparent = button_color.a == 0.0;
let press_offset = if is_pressed { 1.0 } else { 0.0 };
let draw_x = self.x;
let draw_y = self.y + press_offset;
if !is_background_transparent {
// Draw a subtle shadow behind the button.
let shadow_color = Color::new(0.0, 0.0, 0.0, 0.20);
if self.corner_radius > 0.0 {
draw_round_rect(draw_x, draw_y + 2.0, self.width, self.height, self.corner_radius, shadow_color);
} else {
draw_rectangle(draw_x, draw_y + 2.0, self.width, self.height, shadow_color);
}
}
// Draw the button with or without rounded corners.
if self.corner_radius > 0.0 {
draw_round_rect(draw_x, draw_y, self.width, self.height, self.corner_radius, button_color);
// Add top highlight and bottom shade to create depth.
if !is_background_transparent {
let highlight = Color::new(1.0, 1.0, 1.0, if is_pressed { 0.10 } else { 0.28 });
let lowlight = Color::new(0.0, 0.0, 0.0, if is_pressed { 0.18 } else { 0.26 });
draw_round_rect_lines(
draw_x + 1.0,
draw_y + 1.0,
self.width - 2.0,
self.height - 2.0,
(self.corner_radius - 1.0).max(0.0),
1.0,
highlight,
);
draw_round_rect_lines(
draw_x,
draw_y,
self.width,
self.height,
self.corner_radius,
1.0,
lowlight,
);
}
// Draw rounded border if enabled.
if self.border {
draw_round_rect_lines(
draw_x,
draw_y,
self.width,
self.height,
self.corner_radius,
self.border_thickness,
self.border_color,
);
}
} else {
draw_rectangle(draw_x, draw_y, self.width, self.height, button_color);
if !is_background_transparent {
// Bevel effect for square buttons.
let top_highlight = Color::new(1.0, 1.0, 1.0, if is_pressed { 0.10 } else { 0.30 });
let bottom_shade = Color::new(0.0, 0.0, 0.0, if is_pressed { 0.20 } else { 0.28 });
draw_line(draw_x + 1.0, draw_y + 1.0, draw_x + self.width - 1.0, draw_y + 1.0, 1.0, top_highlight);
draw_line(draw_x + 1.0, draw_y + 1.0, draw_x + 1.0, draw_y + self.height - 1.0, 1.0, top_highlight);
draw_line(draw_x, draw_y + self.height, draw_x + self.width, draw_y + self.height, 1.0, bottom_shade);
draw_line(draw_x + self.width, draw_y, draw_x + self.width, draw_y + self.height, 1.0, bottom_shade);
}
// Draw regular border if enabled.
if self.border {
draw_rectangle_lines(
draw_x,
draw_y,
self.width,
self.height,
self.border_thickness,
self.border_color,
);
}
}
// Draw the text with the appropriate font using cached position
let current_text_color = if self.enabled {
if is_hovered {
self.hover_text_color
} else {
self.text_color
}
} else {
// Use a dimmed text color for disabled state
Color::new(self.text_color.r, self.text_color.g, self.text_color.b, 0.5)
};
let lines: Vec<&str> = self.text.split('\n').collect();
let line_height = self.font_size as f32 * 1.2;
let total_height = lines.len() as f32 * line_height;
// Measure baseline offset for the first line (should be similar for all lines)
let baseline_offset = match &self.font {
Some(font) => {
let m = measure_text(lines.get(0).unwrap_or(&"Mg"), Some(font), self.font_size, 1.0);
m.offset_y
},
None => {
let m = measure_text(lines.get(0).unwrap_or(&"Mg"), None, self.font_size, 1.0);
m.offset_y
}
};
let start_y = match self.vertical_align {
// Add a quarter line_height for extra top padding
VerticalAlign::Top => self.y + baseline_offset + press_offset + (line_height * 0.25),
// Add a quarter line_height to visually center the text better
VerticalAlign::Center => self.y + (self.height / 2.0) - (total_height / 2.0) + baseline_offset + press_offset + (line_height * 0.25),
// For bottom, align the last line's baseline near the bottom edge with a small padding
VerticalAlign::Bottom => self.y + self.height - (line_height * 0.25) - total_height + line_height + press_offset,
};
for (i, line) in lines.iter().enumerate() {
let y = start_y + i as f32 * line_height;
let text_width = match &self.font {
Some(font) => measure_text(line, Some(font), self.font_size, 1.0).width,
None => measure_text(line, None, self.font_size, 1.0).width,
};
let x = match self.text_align {
TextAlign::Left => self.x + 8.0,
TextAlign::Center => self.x + (self.width / 2.0) - (text_width / 2.0),
TextAlign::Right => self.x + self.width - text_width - 8.0,
};
match &self.font {
Some(font) => {
draw_text_ex(
line,
x,
y,
TextParams {
font: Some(font),
font_size: self.font_size,
color: current_text_color,
..Default::default()
},
);
},
None => {
draw_text(
line,
x,
y,
self.font_size.into(),
current_text_color,
);
}
}
}
// After drawing, check if the button was clicked
is_hovered && self.enabled && is_mouse_button_released(MouseButton::Left)
}
}
// Function to draw a rectangle with rounded corners - optimized version
fn draw_round_rect(x: f32, y: f32, w: f32, h: f32, radius: f32, color: Color) {
// Precompute corner positions
let top_left = Vec2::new(x + radius, y + radius);
let top_right = Vec2::new(x + w - radius, y + radius);
let bottom_left = Vec2::new(x + radius, y + h - radius);
let bottom_right = Vec2::new(x + w - radius, y + h - radius);
// Draw center rectangle
draw_rectangle(x + radius, y, w - 2.0 * radius, h, color);
// Draw the side rectangles
draw_rectangle(x, y + radius, radius, h - 2.0 * radius, color);
draw_rectangle(x + w - radius, y + radius, radius, h - 2.0 * radius, color);
// Draw the four corner circles (could be batched in a real engine)
draw_circle(top_left.x, top_left.y, radius, color); // Top-left
draw_circle(top_right.x, top_right.y, radius, color); // Top-right
draw_circle(bottom_left.x, bottom_left.y, radius, color); // Bottom-left
draw_circle(bottom_right.x, bottom_right.y, radius, color); // Bottom-right
}
// Function to draw rounded rectangle borders - optimized version
fn draw_round_rect_lines(x: f32, y: f32, w: f32, h: f32, radius: f32, thickness: f32, color: Color) {
// Precompute corner positions
let top_left = Vec2::new(x + radius, y + radius);
let top_right = Vec2::new(x + w - radius, y + radius);
let bottom_left = Vec2::new(x + radius, y + h - radius);
let bottom_right = Vec2::new(x + w - radius, y + h - radius);
// Draw the horizontal and vertical lines
draw_line(top_left.x, y, top_right.x, y, thickness, color); // Top
draw_line(bottom_left.x, y + h, bottom_right.x, y + h, thickness, color); // Bottom
draw_line(x, top_left.y, x, bottom_left.y, thickness, color); // Left
draw_line(x + w, top_right.y, x + w, bottom_right.y, thickness, color); // Right
// Draw the four corner arcs with fewer segments for better performance
let segments = 8; // Reduced from 16 - still looks good but fewer draw calls
let step = std::f32::consts::PI / 2.0 / segments as f32;
// Pre-calculate sin/cos values for angle offsets to avoid redundant calculations
let angles: Vec<(f32, f32)> = (0..=segments)
.map(|i| {
let angle = i as f32 * step;
(angle.cos(), angle.sin())
})
.collect();
// Draw arcs for each corner
// Top-left corner: PI to PI*3/2
for i in 0..segments {
let (cos1, sin1) = angles[i];
let (cos2, sin2) = angles[i+1];
draw_line(
top_left.x - radius * cos1,
top_left.y - radius * sin1,
top_left.x - radius * cos2,
top_left.y - radius * sin2,
thickness,
color
);
}
// Top-right corner: PI*3/2 to PI*2
for i in 0..segments {
let (cos1, sin1) = angles[i];
let (cos2, sin2) = angles[i+1];
draw_line(
top_right.x + radius * sin1,
top_right.y - radius * cos1,
top_right.x + radius * sin2,
top_right.y - radius * cos2,
thickness,
color
);
}
// Bottom-left corner: PI/2 to PI
for i in 0..segments {
let (cos1, sin1) = angles[i];
let (cos2, sin2) = angles[i+1];
draw_line(
bottom_left.x - radius * sin1,
bottom_left.y + radius * cos1,
bottom_left.x - radius * sin2,
bottom_left.y + radius * cos2,
thickness,
color
);
}
// Bottom-right corner: 0 to PI/2
for i in 0..segments {
let (cos1, sin1) = angles[i];
let (cos2, sin2) = angles[i+1];
draw_line(
bottom_right.x + radius * cos1,
bottom_right.y + radius * sin1,
bottom_right.x + radius * cos2,
bottom_right.y + radius * sin2,
thickness,
color
);
}
}
fn lerp_color(c1: Color, c2: Color, factor: f32) -> Color {
Color::new(c1.r * (1.0 - factor) + c2.r * factor, c1.g * (1.0 - factor) + c2.g * factor, c1.b * (1.0 - factor) + c2.b * factor, 1.0)
}
fn shade_color(color: Color, factor: f32) -> Color {
Color::new(
(color.r * factor).clamp(0.0, 1.0),
(color.g * factor).clamp(0.0, 1.0),
(color.b * factor).clamp(0.0, 1.0),
color.a,
)
}