| 342 | } |
| 343 | |
| 344 | std::string StringUtils::wrap(const std::string& text, float scaleX, float maxWidth) |
| 345 | { |
| 346 | if (textWidth(text, scaleX) <= maxWidth) { |
| 347 | return text; |
| 348 | } |
| 349 | std::string dst, line, word; |
| 350 | dst = line = word = ""; |
| 351 | |
| 352 | for (std::string::const_iterator it = text.begin(); it != text.end(); ++it) { |
| 353 | word += *it; |
| 354 | if (*it == ' ') { |
| 355 | // split single words that are bigger than maxWidth |
| 356 | if (StringUtils::textWidth(line + word, scaleX) <= maxWidth) { |
| 357 | line += word; |
| 358 | } |
| 359 | else { |
| 360 | if (StringUtils::textWidth(word, scaleX) > maxWidth) { |
| 361 | line += word; |
| 362 | line = StringUtils::splitWord(line, scaleX, maxWidth); |
| 363 | word = line.substr(line.find('\n') + 1, std::string::npos); |
| 364 | line = line.substr(0, line.find('\n')); // Split line on first newLine; assign second part to word and first to line |
| 365 | } |
| 366 | if (line[line.size() - 1] == ' ') { |
| 367 | dst += line.substr(0, line.size() - 1) + '\n'; |
| 368 | } |
| 369 | else { |
| 370 | dst += line + '\n'; |
| 371 | } |
| 372 | line = word; |
| 373 | } |
| 374 | word = ""; |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | // "Another iteration" of the loop b/c it probably won't end with a space. |
| 379 | // If it does, no harm done. |
| 380 | if (StringUtils::textWidth(line + word, scaleX) <= maxWidth) { |
| 381 | dst += line + word; |
| 382 | } |
| 383 | else { |
| 384 | if (StringUtils::textWidth(word, scaleX) > maxWidth) { |
| 385 | line += word; |
| 386 | line = StringUtils::splitWord(line, scaleX, maxWidth); |
| 387 | word = line.substr(line.find('\n') + 1, std::string::npos); |
| 388 | line = line.substr(0, line.find('\n')); |
| 389 | } |
| 390 | if (line[line.size() - 1] == ' ') { |
| 391 | dst += line.substr(0, line.size() - 1) + '\n' + word; |
| 392 | } |
| 393 | else { |
| 394 | dst += line + '\n' + word; |
| 395 | } |
| 396 | } |
| 397 | return dst; |
| 398 | } |
| 399 | |
| 400 | float StringUtils::textHeight(const std::string& text, float scaleY) |
| 401 | { |