loadFont method

BitmapFont loadFont(
  1. String path,
  2. double size, {
  3. bool antiAlias = true,
  4. String containedAsciiCharacters = BitmapFont.extendedAscii,
})

Loads a TrueType Font and creates BitmapFont out of it.

  • path: The path to the font file (e.g., .ttf, .woff2).
  • size: The desired font size in pixels.
  • antiAlias: Whether to use anti-aliasing when rendering the font atlas. Defaults to true.
  • containedAsciiCharacters: A string of characters to include in the font atlas. Defaults to BitmapFont.extendedAscii.

Returns the loaded or cached BitmapFont.

Implementation

BitmapFont loadFont(
  String path,
  double size, {
  bool antiAlias = true,
  String containedAsciiCharacters = BitmapFont.extendedAscii,
}) {
  var font = BitmapFont(_gl);

  var fontName = path.replaceAll("/", "").replaceAll(".", "");
  var hash = "${path}_${size}_${antiAlias}_$containedAsciiCharacters".hashCode;

  if (_fontCache.containsKey(hash)) {
    return _fontCache[hash]!;
  } else {
    _fontCache[hash] = font;
    load<ByteBuffer?>(
      path,
      _loadingInfo,
      responseType: "arraybuffer",
      onLoad: (response, complete, error) {
        var fontBytes = (response as JSArrayBuffer).toDart;
        final FontFace fontFace = FontFace(fontName, fontBytes.toJS);
        try {
          document.fonts.add(fontFace);
        } catch (e) {
          // NOTE(jochen): I don't know why but on Firefox this throws an Invalid Type
          // exception. But if we ignore it, everythings seems to work.
          // My assumptions it that firefox returns null instead of a
          // FontFaceSet Object that is defined in the standard and Dart
          // expects that return object.
        }
        font.generateAtlas(fontName, size, antiAlias, containedAsciiCharacters);
        complete(fontBytes);
      },
    );
  }

  return font;
}