hgeFont::GetStringWidth
Calculate the pixel width of a text string when rendered.
Synopsis
float hgeFont::GetStringWidth(const char *string, bool bMultiline = true);
Parameters
- string — The text string to measure
- bMultiline — If true, returns the width of the widest line; if false, treats as single line
Returns
The width in pixels that the string would occupy when rendered with this font.
Description
Use this function to determine how much horizontal space text will need. This is useful for:
- Centering text
- Right-aligning text
- Checking if text fits in a UI element
- Text wrapping calculations
Example
hgeFont *font = new hgeFont("font.fnt");
const char *text = "Score: 12345";
float width = font->GetStringWidth(text);
// Center the text on screen
float screenWidth = 800;
float x = (screenWidth - width) / 2.0f;
font->Render(x, 100, HGETEXT_LEFT, text);
Right-Aligned Text
float rightEdge = 750;
float width = font->GetStringWidth("Game Over");
font->Render(rightEdge - width, 200, HGETEXT_LEFT, "Game Over");
Multiline Text
For text with newline characters:
const char *text = "Line 1\nLonger Line 2\nLine 3";
// Get widest line
float maxWidth = font->GetStringWidth(text, true);
// Get total width ignoring newlines (less common)
float totalWidth = font->GetStringWidth(text, false);