From 4e46790eda581deafd55d4677c57fad2c6ebab2d Mon Sep 17 00:00:00 2001 From: gilesp1729 Date: Tue, 9 Jul 2024 14:58:37 +1000 Subject: [PATCH] Make Adafruit_GFX_Button::drawButton work with custom fonts by using getTextBounds to obtain the text bounds. --- Adafruit_GFX.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Adafruit_GFX.cpp b/Adafruit_GFX.cpp index af989002..da5848fa 100644 --- a/Adafruit_GFX.cpp +++ b/Adafruit_GFX.cpp @@ -1674,6 +1674,8 @@ void Adafruit_GFX_Button::initButtonUL(Adafruit_GFX *gfx, int16_t x1, /**************************************************************************/ void Adafruit_GFX_Button::drawButton(bool inverted) { uint16_t fill, outline, text; + int16_t x, y; + uint16_t w, h; if (!inverted) { fill = _fillcolor; @@ -1688,11 +1690,16 @@ void Adafruit_GFX_Button::drawButton(bool inverted) { uint8_t r = min(_w, _h) / 4; // Corner radius _gfx->fillRoundRect(_x1, _y1, _w, _h, r, fill); _gfx->drawRoundRect(_x1, _y1, _w, _h, r, outline); - - _gfx->setCursor(_x1 + (_w / 2) - (strlen(_label) * 3 * _textsize_x), - _y1 + (_h / 2) - (4 * _textsize_y)); _gfx->setTextColor(text); _gfx->setTextSize(_textsize_x, _textsize_y); + // System font is drawn from the upper left, but custom fonts are + // drawn from the lower left. Adjust by the Y returned from getTextBounds(). + _gfx->getTextBounds(_label, _x1, _y1, &x, &y, &w, &h); + _gfx->setCursor + ( + _x1 + (_w / 2) - (w / 2), + _y1 + (_h / 2) - (h / 2) + (_y1 - y) + ); _gfx->print(_label); }