Skip to content

Commit

Permalink
Added Text::DrawWrappedText
Browse files Browse the repository at this point in the history
  • Loading branch information
bXi committed Sep 15, 2024
1 parent 381a26a commit c8b6b74
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
24 changes: 24 additions & 0 deletions text/texthandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,27 @@ TextureAsset Text::_drawTextToTexture(Font font, std::string textToDraw, Color c

return tex;
}

void Text::_drawWrappedText(Font font, vf2d pos, std::string textToDraw, float maxWidth, Color color) {

std::stringstream ss(textToDraw);
std::string word;
std::string currentLine;

while (ss >> word) {
std::string testLine = currentLine.empty() ? word : currentLine + " " + word;
float testLineWidth = MeasureText(font, testLine);

if (testLineWidth <= maxWidth) {
currentLine = testLine;
} else {
DrawText(font, pos, currentLine, color);
pos.y += GetRenderedTextSize(font, currentLine).y;
currentLine = word;
}
}

if (!currentLine.empty()) {
DrawText(font, pos, currentLine, color);
}
}
17 changes: 17 additions & 0 deletions text/texthandler.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,21 @@ class Text {
get()._drawText(font, pos, textToDraw, color);
}

/**
* @brief Renders text that is wider than the given width by splitting it at space boundaries.
* The text will be drawn across multiple lines to ensure it fits within the maximum width.
*
* @param font The font to use for rendering the text.
* @param pos The starting position (top-left) to begin rendering the text.
* @param textToDraw The full text string to render, potentially split across multiple lines.
* @param maxWidth The maximum width allowed for each line of text. If a line exceeds this width, it is wrapped.
* @param color The color to use for rendering the text.
*/
static void DrawWrappedText(Font font, vf2d pos, std::string textToDraw, float maxWidth, Color color) {
get()._drawWrappedText(font, pos, textToDraw, maxWidth, color);
}


/**
* @brief Measures the width of the specified text when rendered with the given font.
*
Expand Down Expand Up @@ -68,6 +83,8 @@ class Text {

void _drawText(Font font, vf2d pos, std::string textToDraw, Color color);

void _drawWrappedText(Font font, vf2d pos, std::string textToDraw, float maxWidth, Color color);

int _measureText(Font font, std::string text);

vf2d _getRenderedTextSize(Font font, std::string textToDraw);
Expand Down

0 comments on commit c8b6b74

Please sign in to comment.