fluent2WrapScale function
The text scale at which words in style stand whole in room on at
most lines lines, each word whole on its line (never "Calenda" over
"r"): fluent2FitScale's one-line scale (never under 1) where the words
then break into lines or fewer, else the largest scale at which they
do, never under least (a page's long name on a phone: iOS shrinks a
title whole before it would cut it).
Implementation
double fluent2WrapScale(
BuildContext context,
String words,
TextStyle style,
double room, {
int lines = 2,
double least = 0.75,
}) {
style = _drawn(context, style);
final one = fluent2FitScale(context, [words], style, room, least: 1);
final split = words.split(RegExp(r'\s+')).where((w) => w.isNotEmpty);
// Each word measured at the scale itself: tracking does not grow or
// shrink with the words, so a width is not the unscaled one times scale.
bool whole(double scale) => _widest(split, style, scale) <= room;
bool fits(double scale) {
if (!whole(scale)) return false;
final painter = TextPainter(
text: TextSpan(text: words, style: style),
textDirection: TextDirection.ltr,
textScaler: TextScaler.linear(scale),
maxLines: lines,
)..layout(maxWidth: room);
final held = !painter.didExceedMaxLines;
painter.dispose();
return held;
}
if (!room.isFinite || room <= 0 || fits(one)) return one;
var lo = least < one ? least : one;
var hi = one;
// Past the floor a word longer than the room is drawn smaller still,
// as small as the room asks, rather than broken.
if (!fits(lo)) {
final longest = _widest(split, style);
var word = longest > 0 ? (room / longest * 100).floorToDouble() / 100 : lo;
if (word >= lo) return lo;
while (word > 0.05 && !whole(word)) {
word -= 0.01;
}
return word;
}
for (var i = 0; i < 8; i++) {
final mid = (lo + hi) / 2;
if (fits(mid)) {
lo = mid;
} else {
hi = mid;
}
}
return lo;
}