1 # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
7 ================================================================================
11 **Software and Dependencies:**
14 https://github.com/adafruit/Adafruit_Blinka/releases
16 * Author(s): Melissa LeBlanc-Williams
20 from typing import Union, Tuple, Optional
21 from PIL import ImageFont
22 from displayio import Bitmap
25 from typing import Protocol
27 from typing_extensions import Protocol
29 __version__ = "0.0.0-auto.0"
30 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
33 class FontProtocol(Protocol):
34 """A protocol shared by `BuiltinFont` and classes in ``adafruit_bitmap_font``"""
36 def get_bounding_box(self) -> Union[Tuple[int, int], Tuple[int, int, int, int]]:
37 """Retrieve the maximum bounding box of any glyph in the font.
39 The four element version is ``(width, height, x_offset, y_offset)``.
40 The two element version is ``(width, height)``, in which
41 ``x_offset`` and ``y_offset`` are assumed to be zero.
44 def get_glyph(self, codepoint: int) -> Optional["Glyph"]:
45 """Retrieve the Glyph for a given code point
47 If the code point is not present in the font, `None` is returned.
51 """Simulate a font built into CircuitPython"""
54 self._font = ImageFont.load_default()
55 self._generate_bitmap(0x20, 0x7E)
57 def _generate_bitmap(self, start_range, end_range):
58 char_width, char_height = self.get_bounding_box()
59 self._bitmap = Bitmap(
60 char_width * (end_range - start_range + 1), char_height, 2
62 for character in range(start_range, end_range + 1):
63 ascii_char = chr(character)
64 ascii_mask = self._font.getmask(ascii_char, mode="1")
65 for y in range(char_height):
66 for x in range(char_width):
67 color = ascii_mask.getpixel((x, y))
68 character_position = character - start_range
69 self._bitmap[character_position * char_width + x, y] = (
73 def get_bounding_box(self):
74 """Returns the maximum bounds of all glyphs in the font in
75 a tuple of two values: width, height.
77 return self._font.getsize("M")
79 def get_glyph(self, codepoint):
80 """Returns a `fontio.Glyph` for the given codepoint or None if no glyph is available."""
81 if 0x20 <= codepoint <= 0x7E:
82 glyph_index = codepoint - 0x20
86 bounding_box = self._font.getsize(chr(codepoint))
87 width, height = bounding_box
90 tile_index=glyph_index,
101 """Bitmap containing all font glyphs starting with ASCII and followed by unicode. Use
102 `get_glyph` in most cases. This is useful for use with `displayio.TileGrid` and
103 `terminalio.Terminal`.
108 # pylint: disable=too-few-public-methods, invalid-name, too-many-arguments
110 """Storage of glyph info"""
112 def __init__(self, bitmap, tile_index, width, height, dx, dy, shift_x, shift_y):
118 self.shift_x = shift_x
119 self.shift_y = shift_y
120 self.tile_index = tile_index
123 # pylint: enable=too-few-public-methods, invalid-name, too-many-arguments