| 363 | } |
| 364 | |
| 365 | std::string StringUtils::wrap(const std::string& text, float scaleX, float maxWidth) |
| 366 | { |
| 367 | if (textWidth(text, scaleX) <= maxWidth) { |
| 368 | return text; |
| 369 | } |
| 370 | std::string dst, line, word; |
| 371 | dst = line = word = ""; |
| 372 | |
| 373 | for (std::string::const_iterator it = text.begin(); it != text.end(); ++it) { |
| 374 | word += *it; |
| 375 | if (*it == ' ') { |
| 376 | // split single words that are bigger than maxWidth |
| 377 | if (StringUtils::textWidth(line + word, scaleX) <= maxWidth) { |
| 378 | line += word; |
| 379 | } |
| 380 | else { |
| 381 | if (StringUtils::textWidth(word, scaleX) > maxWidth) { |
| 382 | line += word; |
| 383 | line = StringUtils::splitWord(line, scaleX, maxWidth); |
| 384 | word = line.substr(line.find('\n') + 1, std::string::npos); |
| 385 | line = line.substr(0, line.find('\n')); // Split line on first newLine; assign second part to word and first to line |
| 386 | } |
| 387 | if (line[line.size() - 1] == ' ') { |
| 388 | dst += line.substr(0, line.size() - 1) + '\n'; |
| 389 | } |
| 390 | else { |
| 391 | dst += line + '\n'; |
| 392 | } |
| 393 | line = word; |
| 394 | } |
| 395 | word = ""; |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | // "Another iteration" of the loop b/c it probably won't end with a space. |
| 400 | // If it does, no harm done. |
| 401 | if (StringUtils::textWidth(line + word, scaleX) <= maxWidth) { |
| 402 | dst += line + word; |
| 403 | } |
| 404 | else { |
| 405 | if (StringUtils::textWidth(word, scaleX) > maxWidth) { |
| 406 | line += word; |
| 407 | line = StringUtils::splitWord(line, scaleX, maxWidth); |
| 408 | word = line.substr(line.find('\n') + 1, std::string::npos); |
| 409 | line = line.substr(0, line.find('\n')); |
| 410 | } |
| 411 | if (line[line.size() - 1] == ' ') { |
| 412 | dst += line.substr(0, line.size() - 1) + '\n' + word; |
| 413 | } |
| 414 | else { |
| 415 | dst += line + '\n' + word; |
| 416 | } |
| 417 | } |
| 418 | return dst; |
| 419 | } |
| 420 | |
| 421 | float StringUtils::textHeight(const std::string& text, float scaleY) |
| 422 | { |