Text wrap script

tung's picture

A screenshot of the text wrapper at work

This script can wrap strings given either a character or a pixel width, breaking it into an array of lines.

Handy to side-step the issues with char-by-char word "jumping" with Sphere's text drawing functions.

Features

  • Wrap text by character or pixel widths
  • Specify different fonts to measure by
  • Provide any width; words that don't fit in a full line are cut into multiple lines

Notes

Between now and the creation of this script, Sphere has a new internal function to handle this: Font.wordWrapString(). In fact, I was the one who adapted the internal function. Use that instead of this, unless you really need wrapping by character width.

Also, WordWrapByFontWidth and WordWrapByStrLen don't handle the '\n' character correctly.

Usage

Download TextWrap.js, put it in your game's scripts/ directory, and include it in your main script:

RequireScript("TextWrap.js");

To wrap strings, just feed them into the functions, and get the returned array of lines:

var font = GetSystemFont();
var width = 100;
var message = "This is a long message. It deserves to be wrapped into multiple lines.";
 
var lines = WordWrapByFontWidth(message, font, width);
for (var l = 0; l < lines.length; ++l)
  font.drawText(0, font.getHeight() * l, lines[l]);
 
FlipScreen();
GetKey();

Download