From a468b33d1ec93f7233014758705bb87c078eb20c Mon Sep 17 00:00:00 2001 From: Nebuleon Fumika Date: Wed, 23 Jul 2014 08:29:53 +0000 Subject: [PATCH] When computing the width of multi-line text, split lines and return the longest Along with the newline support in Font::write(), Font::getTextWidth() now splits text along '\n' and returns the width of the longest split. --- src/font.cpp | 27 +++++++++++++++++++++------ src/font.h | 7 +------ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/src/font.cpp b/src/font.cpp index 82c08f8..ce5b35e 100644 --- a/src/font.cpp +++ b/src/font.cpp @@ -49,14 +49,29 @@ Font::~Font() } } -int Font::getTextWidth(const char *text) +int Font::getTextWidth(const string &text) { - if (font) { - int w, h; - TTF_SizeUTF8(font, text, &w, &h); - return w; + if (!font) { + return 1; + } + + int w; + size_t pos = text.find('\n', 0); + if (pos == string::npos) { + TTF_SizeUTF8(font, text.c_str(), &w, nullptr); + return w; + } else { + int maxWidth = 1; + size_t prev = 0; + do { + TTF_SizeUTF8(font, text.substr(prev, pos - prev).c_str(), &w, nullptr); + maxWidth = max(w, maxWidth); + prev = pos + 1; + pos = text.find('\n', prev); + } while (pos != string::npos); + TTF_SizeUTF8(font, text.substr(prev).c_str(), &w, nullptr); + return max(w, maxWidth); } - else return 1; } void Font::write(Surface *surface, const string &text, diff --git a/src/font.h b/src/font.h index 68dde24..ff58ac9 100644 --- a/src/font.h +++ b/src/font.h @@ -22,12 +22,7 @@ public: Font(const std::string &path, unsigned int size); ~Font(); - int getTextWidth(const char *text); - - int getTextWidth(const std::string& text) - { - return getTextWidth(text.c_str()); - } + int getTextWidth(const std::string& text); int getLineSpacing() {