| 1 |
use sdl2::pixels::Color; |
| 2 |
use sdl2::rect::Rect; |
| 3 |
use sdl2::render::{Canvas, TextureQuery}; |
| 4 |
use sdl2::ttf; |
| 5 |
use sdl2::video::Window; |
| 6 |
|
| 7 |
use crate::game_context::GameEvent; |
| 8 |
|
| 9 |
pub struct Button { |
| 10 |
pub rect: Rect, |
| 11 |
pub color: Color, |
| 12 |
pub text: String, |
| 13 |
pub event: GameEvent, |
| 14 |
} |
| 15 |
|
| 16 |
impl Button { |
| 17 |
pub fn new(x: i32, y: i32, width: u32, height: u32, text: &str, event: GameEvent) -> Self { |
| 18 |
Self { |
| 19 |
rect: Rect::new(x, y, width, height), |
| 20 |
color: Color::RGB(0, 120, 215), |
| 21 |
text: text.to_string(), |
| 22 |
event, |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
pub fn draw( |
| 27 |
&mut self, |
| 28 |
canvas: &mut Canvas<Window>, |
| 29 |
font: &ttf::Font<'static, 'static>, |
| 30 |
) -> Result<(), String> { |
| 31 |
canvas.set_draw_color(self.color); |
| 32 |
canvas.fill_rect(self.rect)?; |
| 33 |
|
| 34 |
let surface = font |
| 35 |
.render(&self.text) |
| 36 |
.blended(Color::RGB(255, 255, 255)) |
| 37 |
.map_err(|e| e.to_string())?; |
| 38 |
|
| 39 |
let texture_creator = canvas.texture_creator(); |
| 40 |
let texture = texture_creator |
| 41 |
.create_texture_from_surface(&surface) |
| 42 |
.map_err(|e| e.to_string())?; |
| 43 |
|
| 44 |
let TextureQuery { width, height, .. } = texture.query(); |
| 45 |
|
| 46 |
let text_rect = Rect::new( |
| 47 |
self.rect.x() + (self.rect.width() as i32 - width as i32) / 2, |
| 48 |
self.rect.y() + (self.rect.height() as i32 - height as i32) / 2, |
| 49 |
width, |
| 50 |
height, |
| 51 |
); |
| 52 |
|
| 53 |
canvas.copy(&texture, None, Some(text_rect))?; |
| 54 |
Ok(()) |
| 55 |
} |
| 56 |
|
| 57 |
pub fn is_clicked(&self, mouse_x: i32, mouse_y: i32) -> bool { |
| 58 |
self.rect.contains_point((mouse_x, mouse_y)) |
| 59 |
} |
| 60 |
} |