Hello everyone!
I have a set of different shapes like rectangles, circles, etc., and I need to align the text associated with each shape perfectly in the center of the shape. I wrote the following algorithm to determine offsets for the x and y axes respectively:
sf::Text text = shape.getText();
float textOffsetX = (shape.getShape()->getGlobalBounds().width - text.getGlobalBounds().width) / 2;
float textOffsetY = (shape.getShape()->getGlobalBounds().height - text.getGlobalBounds().height) / 2;
text.setPosition(shapeOffsetX + textOffsetX, shapeOffsetY + textOffsetY);
As a result, the text inside each shape is perfectly aligned horizontally but wrong vertically. Please find the screenshot in attachments. I do not know how I can put it here
My shapes are moving, so in addition to text offsets, there are also shape offsets. It does not have to matter. I have also tried two more ways, but the result is the same:
1.sf::Text text = shape.getText();
float textOffsetX = (shape.getShape()->getGlobalBounds().width - text.getGlobalBounds().width) / 2;
auto glyph = text.getFont()->getGlyph(text.getString()[0], text.getCharacterSize(), false);
float textOffsetY = (shape.getShape()->getGlobalBounds().height - glyph.bounds.height) / 2;
text.setPosition(shapeOffsetX + textOffsetX, shapeOffsetY + textOffsetY);
2.sf::Text text = shape.getText();
float textOffsetX = (shape.getShape()->getGlobalBounds().width - text.getGlobalBounds().width) / 2;
float textOffsetY = (shape.getShape()->getGlobalBounds().height - text.getCharacterSize()) / 2;
text.setPosition(shapeOffsetX + textOffsetX, shapeOffsetY + textOffsetY);
Could you please help me with this question?