wrapTextHalo static method

List<String> wrapTextHalo(
  1. String text,
  2. int maxWidth, {
  3. int fontSize = 8,
})

Word-wrap text to maxWidth pixels using Halo's monospace metrics.

Implementation

static List<String> wrapTextHalo(String text, int maxWidth,
    {int fontSize = 8}) {
  final charsPerLine = maxWidth ~/ ((fontSize ~/ 8) * haloCharWidth);
  List<String> output = List.empty(growable: true);

  for (String line in text.split("\n")) {
    String trimmedLine = line.trim();
    if (trimmedLine.isEmpty) {
      continue;
    } else if (trimmedLine.length <= charsPerLine) {
      output.add(trimmedLine);
    } else {
      String thisLine = "";
      for (String word in trimmedLine.split(" ")) {
        // hard-break words longer than a whole line
        while (word.length > charsPerLine) {
          if (thisLine.isNotEmpty) {
            output.add(thisLine);
            thisLine = "";
          }
          output.add(word.substring(0, charsPerLine));
          word = word.substring(charsPerLine);
        }
        if (thisLine.isEmpty) {
          thisLine = word;
        } else if (thisLine.length + 1 + word.length <= charsPerLine) {
          thisLine += " $word";
        } else {
          output.add(thisLine);
          thisLine = word;
        }
      }
      if (thisLine.isNotEmpty) {
        output.add(thisLine.trim());
      }
    }
  }
  return output;
}