/** * @brief Button -- constructor to make complete button * @param access_name -- name used for identification of element * @param txtr -- contains text to render or path to icon; will be placed in center of button * @param form -- size and position of button * @param margin -- margins inside button * @param content -- marks content that will be placed in button (text, icon), defaulted to text */ Button::Button(std::string access_name, std::string txtr, SDL_Rect form, Padding margin, Button::Content content) : Widget(access_name, default_back_path, form, margin) , font_color(default_font_color) , listener(SDL_MOUSEBUTTONDOWN) { font = TTF_OpenFont(default_font_path.c_str(), default_font_size); // creating texture with text if content marked as text if (content == text) { this->txtr = Texture::ptr(new Texture(txtr, font, font_color, form.x + margin.left, form.y + margin.top)); // else creating texture with image if content marked as icon } else if (content == icon) { this->txtr = Texture::ptr(new Texture(txtr, form.x + margin.left, form.y + margin.top)); } // centering content of button SDL_Rect txtr_form = this->txtr->get_form(); int centered_w = txtr_form.w; if (centered_w > (form.w - margin.left - margin.right)) centered_w = (form.w - margin.left - margin.right); int centered_h = txtr_form.h; if (centered_h > (form.h - margin.top - margin.bottom)) centered_h = (form.h - margin.top - margin.bottom); int centered_x = form.x + ((form.w - margin.left - margin.right)/2 - (centered_w / 2)); int centered_y = form.y + ((form.h - margin.top - margin.bottom)/2 - (centered_h / 2)); this->txtr->set_form({centered_x, centered_y, centered_w, centered_h}); listener.set_handler([this] (SDL_Event& event) -> void { // if clicked this button and on_click_handler is defined if (is_point_in({event.button.x, event.button.y}) && on_click_handler) { on_click_handler(); } }); }
bool button::handle_event(const SDL_Event & e) { switch (e.type) { case SDL_MOUSEBUTTONDOWN: down_tick = SDL_GetTicks(); return true; case SDL_MOUSEBUTTONUP: { if (button_down_here(e.button.button)) { if (on_click_handler) { on_click_handler(this); return true; } } } break; default: break; } return false; } // button::handle_event()