glyph method
codePoint drawn the way Flutter's Icon draws it at size: the
glyph set at fontSize: size, height: 1, centered in a size square.
Null when the font has no such glyph; IconGlyph.isEmpty when it has
no ink.
Implementation
IconGlyph? glyph(int codePoint, double size) {
final gid = _cmap[codePoint];
if (gid == null || gid == 0) return null;
final scale = size / unitsPerEm;
final advance = _advances.isEmpty
? unitsPerEm
: _advances[math.min(gid, _advances.length - 1)];
// height: 1 makes the line exactly fontSize tall, split between ascent
// and descent in the font's own proportions.
final lineUnits = ascender - descender;
final baseline = lineUnits == 0 ? size : size * ascender / lineUnits;
final dx = (size - advance * scale) / 2;
final commands = _outline(gid);
double minX = double.infinity, minY = double.infinity;
double maxX = -double.infinity, maxY = -double.infinity;
void include(double x, double y) {
minX = math.min(minX, x);
maxX = math.max(maxX, x);
minY = math.min(minY, y);
maxY = math.max(maxY, y);
}
// Bounds of the outline itself, curve extremes included but not control
// points: Figma sizes a vector the same way, so the two agree.
final points = <List<double>>[];
var cx = 0.0, cy = 0.0;
for (final c in commands) {
final m = <double>[
for (var i = 0; i < c.args.length; i += 2) ...[
dx + c.args[i] * scale,
baseline - c.args[i + 1] * scale,
],
];
points.add(m);
if (m.isEmpty) continue;
final ex = m[m.length - 2], ey = m[m.length - 1];
include(ex, ey);
if (c.op == 'Q') {
for (final t in [
_quadExtreme(cx, m[0], ex),
_quadExtreme(cy, m[1], ey),
]) {
if (t == null) continue;
include(_quad(cx, m[0], ex, t), _quad(cy, m[1], ey, t));
}
} else if (c.op == 'C') {
for (final t in [
..._cubicExtremes(cx, m[0], m[2], ex),
..._cubicExtremes(cy, m[1], m[3], ey),
]) {
include(_cubic(cx, m[0], m[2], ex, t), _cubic(cy, m[1], m[3], ey, t));
}
}
cx = ex;
cy = ey;
}
if (commands.isEmpty) {
return IconGlyph._(path: '', x: 0, y: 0, width: 0, height: 0);
}
String n(double v) {
final s = v.toStringAsFixed(3);
return s.contains('.')
? s.replaceFirst(RegExp(r'0+$'), '').replaceFirst(RegExp(r'\.$'), '')
: s;
}
final d = StringBuffer();
for (var i = 0; i < commands.length; i++) {
final c = commands[i];
if (d.isNotEmpty) d.write(' ');
d.write(c.op);
final p = points[i];
for (var j = 0; j < p.length; j += 2) {
d.write(' ${n(p[j] - minX)} ${n(p[j + 1] - minY)}');
}
}
return IconGlyph._(
path: d.toString(),
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY,
);
}